0

MySQLを使用したPDO; PHPv。5.2.14

ユーザー入力用のテキストボックスと、著者またはタイトルのいずれかで検索するためのラジオボタンを備えた検索フォームがあります。出力は最終的にページ付けされます。

私はPDOに不慣れで、まだ基本を吸収しています。ですから、私が正しい方向に進んでいるかどうかを知っていただければ幸いです。基本的なSQLを取得したので、問題はありませんが、変数を列として配置したいと思います。PDOはテーブル名または列名をパラメーターとして受け入れないことを学びました。だから私は次のことを試しました:

修正を加えて編集し、バインディングパラメータのバリエーションを追加しました

try {

if (isset($_POST['submit1'])) {
    echo '<pre>', print_r ($_POST, TRUE), '</pre>';

$selected_radio = $_POST['text_search'];

if ($selected_radio == 'author') {
   $_SESSION['where_field'] = 'author';    
}
    else if ($selected_radio == 'title') {
      $_SESSION['where_field'] = 'title';
    }
}

 if (!empty($_POST['search_term'])){
    $_SESSION['search_term'] =   filter_var($_POST['search_term'], FILTER_SANITIZE_STRING);
     }else {
        echo "please enter a search term.";
    }

echo "search term: " . $_SESSION['search_term'] . "<br />";

// Find out how many items are in the table
$sql = "SELECT COUNT(*) as num_books from t_books where ". 
     $_SESSION['where_field'] ." LIKE :search_term';  
$prep = $dbh->prepare($sql);
$num = $prep->execute(array(':search_term' => '%'.$_SESSION['search_term']. '%'));

 var_dump($prep);
  echo "<br />";
   if ($num) {
    $total = $prep->fetchColumn();        
    }

    echo "total: $total <br />";

変化:

$sql = "SELECT COUNT(*) as num_books from t_books where ". $_SESSION['where_field'] . " LIKE
 CONCAT('%',:search_term,'%')";
$prep = $dbh->prepare($sql);
$prep->bindParam(':search_term', $_SESSION['search_term'], PDO:: PARAM_STR);
$prep->execute(); 

if ($prep) {
    $total = $prep->fetchColumn();        
}

文字列の引用の問題:私の最初の試みとエラー

$sql = 'SELECT COUNT(*) as num_books from t_books where '". $_SESSION['where_field'] ."' 
LIKE :search_term';  
Parse Error

$sql = "SELECT COUNT(*) as num_books from t_books where $_SESSION['where_field'] 
LIKE :search_term";
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING'

$sql = "SELECT COUNT(*) as num_books from t_books where ". $_SESSION['where_field'] . " 
LIKE :search_term";
Notice: Undefined index: where_field
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  'LIKE '%the%'' 
at line 1

$sql = 'SELECT COUNT(*) as num_books from t_books where ' . "$where_field" . 'LIKE :search_term';
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 'LIKE '%the%'' at 
line 1

引用符で何が起こっているのかを追跡するのは難しいと感じています。コースの修正と洞察をありがとうございます。

4

2 に答える 2

2

そのはず:

$sql = "SELECT COUNT(*) as num_books 
       from t_books 
       where " . $_SESSION['where_field'] . " LIKE :search_term"; 
于 2012-08-28T16:20:59.457 に答える
1

これを試して。

$sql = "SELECT COUNT(*) as num_books from t_books where " . $_SESSION['where_field'] . " LIKE :search_term";  
于 2012-08-28T16:21:46.900 に答える