0

我正在尝试适应PDO,但无法使其正常工作。

下面是一个基本搜索框的脚本:

<?php
$sth= new connection();

if (isset($_GET['search'])) {

   $search_query = $_GET['search'];
   $search_query  = htmlentities($search_query);

   $result=$sth->con->prepare("SELECT firstname, lastname  FROM users WHERE
       firstname LIKE '%" . $search_query . "%' OR
       lastname LIKE '%" . $search_query . "%' OR
       LIMIT 25");

  $result->bindParam(1, $search_query, PDO::PARAM_STR, 12);     

  foreach ($result as $row) {
  $firstname = $row["firstname"];
  $lastname = $row["lastname"];


  if (!($result) == 0) {
  ?>
     <div="foo">Here are your results:</div>

  <?php
  } else {
  ?>

     <div="bar">No results!</div>
<?php
  }
}
?>

这是我得到的错误:

fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[]: <<Unknown error>>

我究竟做错了什么 ?

ps:$sth适用于其他查询。

4

2 回答 2

2

首先,你直接连接 sql 字符串,所以你不需要bindParam. 您应该执行以下操作:

$result=$sth->con->prepare("SELECT firstname, lastname  FROM users WHERE
    firstname LIKE ? OR
    lastname LIKE ? OR
    LIMIT 25");
$result->bindValue(1, "%$search_query%", PDO::PARAM_STR);                     
$result->bindValue(2, "%$search_query%", PDO::PARAM_STR);  

其次,您必须调用PDOStatement::execute才能执行该语句。

$result->execute();

第三,这里和那里还有一些小问题,尝试阅读手册并检查示例......

于 2013-09-29T02:49:35.853 回答
2

Right order and execute is required

$con = new PDO('...');
$stmt = $conn->prepare('...');
$stmt->bindParam('...');
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
    //...
}

PDO Connection, PDO Prepare, PDO Bind, PDO fetchAll and a tutorial.

于 2013-09-29T02:53:26.977 回答