0

带有 MySQL 的 PDO;PHP v. 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 回答