mysqli vs msql和PDO连接

时间:2017-09-10 14:58:26

标签: mysql mysqli content-management-system php-7

我正在尝试制作一个基本的cms,遵循这里的教程:Cms Tut

在Article.php中,他使用带有PDO连接的mysql_escape_string($ order),现在从php 7中删除,我改为mysqli_escape_string($ order)并以某种方式进行处理,但是给出了2个参数的错误。我是php的新手,但是当我搜索时,我认为问题在于PDO连接,我不能把连接作为第二个参数。有什么想法和想法吗?在此先感谢。

以下是代码:

public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
   $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
   $sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
           ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

   $st = $conn->prepare( $sql );
   $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
   $st->execute();
   $list = array();

   while ( $row = $st->fetch() ) {
     $article = new Article( $row );
     $list[] = $article;
   }

   // Now get the total number of articles that matched the criteria
   $sql = "SELECT FOUND_ROWS() AS totalRows";
   $totalRows = $conn->query( $sql )->fetch();
   $conn = null;
   return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
 }

更新代码后,创建一个mysqli连接,在浏览器中有,这个错误:mysqli_connect():( HY000 / 2002):php_network_getaddresses:getaddrinfo failed:没有这样的主机是已知的。

并且在服务器错误日志中也是这样的:在布尔值上调用成员函数real_escape_string()

更新代码为:

public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
   $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
   $link = mysqli_connect(DB_USERNAME, DB_PASSWORD, DB_DSN);

   $sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
           ORDER BY " . $link->real_escape_string($order) . " LIMIT :numRows";

   $st = $conn->prepare( $sql );
   $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
   $st->execute();
   $list = array();

   while ( $row = $st->fetch() ) {
     $article = new Article( $row );
     $list[] = $article;
   }

   // Now get the total number of articles that matched the criteria
   $sql = "SELECT FOUND_ROWS() AS totalRows";
   $totalRows = $conn->query( $sql )->fetch();
   $conn = null;
   return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
 }

1 个答案:

答案 0 :(得分:0)

您需要选择一个 Foo foo = new Foo(); Zoo zoo = new Zoo(); foo.setZoo(zoo); router.navigateByUrl(myApiUrl+"/"+tabId+"?"+itemId, { skipLocationChange: true }); mysql_(不要选择mysqli_)。

您不能混用PDOmysql_

您不需要使用PDO来保护PDO免受SQL注入;它有自己的方法(你已经用于mysqli_ !!)。

有关使用PDO处理特殊字符的指导,请参阅How can I prevent SQL injection in PHP?