PDO列变量LiKE查询QUOTES

时间:2012-08-28 16:16:42

标签: php mysql pdo prepared-statement

使用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();        
}

STRING QUOTE PROBLEM:我最初的尝试和错误

$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

我发现很难跟踪报价的内容。感谢您提供的任何课程更正和见解。

2 个答案:

答案 0 :(得分:2)

它应该是:

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

答案 1 :(得分:1)

试试这个。

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