Php 使用PDO查询代替mysql,即已弃用
众所周知,Mysql已在php v7.0中删除,我尝试使用以下示例使用pdo通过datatables获取数据(服务器端),但Mysql中的Mysql需要pdo中的Mysql: 代码: 栏目:Php 使用PDO查询代替mysql,即已弃用,php,mysql,pdo,datatables,Php,Mysql,Pdo,Datatables,众所周知,Mysql已在php v7.0中删除,我尝试使用以下示例使用pdo通过datatables获取数据(服务器端),但Mysql中的Mysql需要pdo中的Mysql: 代码: 栏目: /* 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
/* 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 );
我看到了一个问题:
$sWhere .= $aColumns[$i]." LIKE '%".$db_con->quote($_GET['sSearch_'.$i])."%' ";
PDO::quote()
函数的输出与以前不推荐使用的mysql\u real\u escape\u string()函数的输出不同
假设字符串为“O'Reilly”,需要转义撇号字符
mysql\u real\u escape\u string(“O'Reilly”)
将返回:
O\'Reilly
'O\'Reilly'
而$db\u con->quote(“O'Reilly”)
将返回:
O\'Reilly
'O\'Reilly'
函数的作用是:在字符串的开头和结尾添加字符串分隔符。这使得它的工作原理与MySQL内置函数相同
因此,当您使用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编码,但我经常打开参考文档。如果要切换到PDO(太好了!),则需要将所有内容切换到PDO。你不能把它和mysql混在一起。你不能有任何mysql\uz
code。您需要选择mysqli
或pdo
它们不一样mysqli
也不只是可以与mysql\uu
@Don'tPanic互换是的,我知道,但我怎么做我不知道该用什么来代替mysqli,目前pdo的初学者也一样……但这不是一个好的功能。要真正利用PDO提供的功能,您应该使用prepare
和execute
并绑定您的参数。查看您现有的代码(看起来已经有一些CRUD抽象)以及可选的限制和按属性排序;您可能应该在PDO上选择一个抽象库。这比为?
占位符和->execute([…])
或类型转换限制标量或白名单列名(实际上无法绑定)管理可选参数要省力。感谢您提供这么好的信息!终于成功了