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 に答える