php - 使用 PDO 查询代替 mysql 即弃用

标签 php mysql pdo datatables

众所周知,Mysql 已在 php v7.0 中删除,我正在尝试使用 pdo 来获取数据(服务器端),使用以下示例的数据表,但它在 mysql 中需要在 pdo 中使用它: 代码:

列:

/* Array of database columns which should be read and sent back to DataTables. Use a space where
 * you want to insert a non-database field (for example a counter or static image)
 */
$aColumns = array( 'first_name', 'last_name', 'position', 'office', 'salary' );

/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id";

/* DB table to use */
$sTable = "datatables_demo";

创建 PDO 连接:

$db_host = "localhost";
$db_name = "sadad";
$db_user = "root";
$db_pass = "root";

try{
    $db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
    echo $e->getMessage();
}

以下代码:

$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
    $sLimit = "LIMIT ".$db_con->quote( $_GET['iDisplayStart'] ).", ".
        $db_con->quote( $_GET['iDisplayLength'] );
}


/*
 * Ordering
 */
if ( isset( $_GET['iSortCol_0'] ) )
{
    $sOrder = "ORDER BY  ";
    for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
    {
        if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
        {
            $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                ".$db_con->quote( $_GET['sSortDir_'.$i] ) .", ";
        }
    }

    $sOrder = substr_replace( $sOrder, "", -2 );
    if ( $sOrder == "ORDER BY" )
    {
        $sOrder = "";
    }
}


/* 
 * Filtering
 * NOTE this does not match the built-in DataTables filtering which does it
 * word by word on any field. It's possible to do here, but concerned about efficiency
 * on very large tables, and MySQL's regex functionality is very limited
 */
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
    $sWhere = "WHERE (";
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        $sWhere .= $aColumns[$i]." LIKE '%".$db_con->quote( $_GET['sSearch'] )."%' OR ";
    }
    $sWhere = substr_replace( $sWhere, "", -3 );
    $sWhere .= ')';
}

/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
    if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
    {
        if ( $sWhere == "" )
        {
            $sWhere = "WHERE ";
        }
        else
        {
            $sWhere .= " AND ";
        }
        $sWhere .= $aColumns[$i]." LIKE '%".$db_con->quote($_GET['sSearch_'.$i])."%' ";
    }
}
$my = str_replace(" , ", " ", implode(", ", $aColumns));

/*
 * SQL queries
 * Get data to display
 */
$sQuery = $db_con->query("SELECT {$my} FROM   {$sTable} {$sWhere} {$sOrder} {$sLimit}")->fetchAll(); 
//$rResult = ( $sQuery );

/* Data set length after filtering */
$sQuery = "
    SELECT FOUND_ROWS()
";
//$rResultFilterTotal = $sQuery;
$aResultFilterTotal = $sQuery;
$iFilteredTotal = $aResultFilterTotal[0];

/* Total data set length */
$sQuery = "
    SELECT COUNT(".$sIndexColumn.")
    FROM   $sTable
";
$rResultTotal = $db_con->query( $sQuery ) or die(mysql_error());
$aResultTotal = $rResultTotal->fetchAll();
$iTotal = $aResultTotal[0];


/*
 * Output
 */
$output = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "aaData" => array()
);

while ( $aRow = $rResult->fetchAll() )
{
    $row = array();
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( $aColumns[$i] == "version" )
        {
            /* Special output formatting for 'version' column */
            $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
        }
        else if ( $aColumns[$i] != ' ' )
        {
            /* General output */
            $row[] = $aRow[ $aColumns[$i] ];
        }
    }
    $output['aaData'][] = $row;
}

echo json_encode( $output );

错误: 但是我收到了错误,我不知道上面要更改什么,有点开始使用 pdo,将不胜感激带有代码的更新答案:

更新代码现在收到以下错误

[28-Aug-2018 16:58:39 UTC] PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''asc' LIMIT '0', '50'' at line 2' in C:\MAMP\htdocs\backend\my.php:131
Stack trace:
#0 C:\MAMP\htdocs\backend\my.php(131): PDO->query('SELECT first_na...')
#1 {main}
  thrown in C:\MAMP\htdocs\backend\my.php on line 131
**ERROR:**

最佳答案

我在这里看到一个问题:

$sWhere .= $aColumns[$i]." LIKE '%".$db_con->quote($_GET['sSearch_'.$i])."%' ";

PDO::quote() 函数的输出与旧的已弃用的 mysql_real_escape_string() 函数不同。

假设您的字符串是“O'Reilly”并且您需要转义撇号字符。

mysql_real_escape_string("O'Reilly") 将返回:

    O\'Reilly

$db_con->quote("O'Reilly") 将返回:

    'O\'Reilly'

quote() 函数将字符串定界符添加到字符串的开头和结尾。这使得它与 MySQL 内置函数一样工作 QUOTE()

所以当你按照你的方式使用 PDO::quote() 时:

$sWhere .= $aColumns[$i]." LIKE '%".$db_con->quote($_GET['sSearch_'.$i])."%' ";

生成的 SQL 子句如下所示:

... WHERE mycolumn LIKE '%'search'%' ...

这是行不通的。你需要它是:

... WHERE mycolumn LIKE '%search%' ...

一种解决方案是添加 % 通配符,然后引用结果:

$sWhere .= $aColumns[$i]." LIKE ".$db_con->quote('%'.$_GET['sSearch_'.$i].'%') ;

现在它利用 PDO::quote() 添加字符串定界符。

顺便说一下,我发现所有的 . 字符串连接让 PHP 看起来很糟糕。很难编写代码,也很难阅读和调试它。我更喜欢直接在字符串中使用变量。不要害怕用两行代码完成工作。在一行中塞入太多内容对于代码可读性而言并不总是最好的。

$pattern = $db_con->quote("%{$_GET["sSearch_$i"]}%");

$sWhere .= "{$aColumns[$i]} LIKE {$pattern}";

但还有另一种更简单、更安全的方法。

使用查询参数而不是转义/引用。

$params[] = "%{$_GET["sSearch_$i"]}%";

$sWhere .= "{$aColumns[$i]} LIKE ?";

然后……

$stmt = $db_con->prepare($sQuery);
$stmt->execute($params);
while ($row = $stmt->fetchAll()) {
    ...
}

使用参数比使用转义/引用更简单。您不必胡思乱想,想知道您的引号是否适当平衡,因为参数占位符 ? 周围不需要字符串定界符。

如果您正在学习 PDO,我建议您阅读以下内容:

两者都很重要且有用。引用文档不太适合学习,但在你完成教程后它们很有用,可以提醒自己语法、参数、返回值等。我已经完成了大量的 PDO 编码,但我经常打开引用文档。

关于php - 使用 PDO 查询代替 mysql 即弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062527/

相关文章:

javascript - 在 select 选项的 onchange function() 中传递多个名称

php - 如何在 PHP 中将数据从主数组传递到多个数组

sql - mysql选择不重复的最小值

php - 试图找到一种简单的方法让 PHP 和 Mysql DB 为 PHP5.5 做数学运算(AVG MIN MAX)

php - 检测 Mac 用户 - htaccess

mysql - 表上的更新更改另一个表中的字段

mysql如何输出auto_increment计数器值

php - PDO utf8_encoding 我的文本字符串在 INSERT 中两次?

php - 如何拦截 PDO 调用?

php - magento - 快速搜索返回所有产品