dpt8910 2013-04-02 17:52
浏览 51
已采纳

在具有多个字段的预准备语句中仅查询一个参数

I am getting values from multiple form fields and using a prepared statement to query the database. While the code below works for criteria entered in a single field, it doesn't return any values if I enter in more than one field. It seems the reason is that page is only processing the last field entered. when I echo the value in $params before $results->execute(array($params)); I only get one value...

Here's what I have:

<?php


$dbhost     = "ip_address";
$dbname     = "db_name";
$dbuser     = "db_login";
$dbpass     = "db_pass"; 

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

    $query = "SELECT * FROM tbl_name WHERE 1=1";

    foreach ($_POST as $k => $v) 
    { 
      if(!empty($v)) {
        $query .= " AND $k LIKE ?";
        $params[] = '%'.$v;     
      }  
    }   

    $results = $conn->prepare($query);
    $results->execute($params);

    $results->bindColumn(1, $no);
    $results->bindColumn(2, $date);
    $results->bindColumn(3, $name);
    $results->bindColumn(4, $id);
    $results->bindColumn(5, $path);

?>

EDIT:

I changed the code above to the working script

  • 写回答

1条回答 默认 最新

  • douji6896 2013-04-02 18:14
    关注

    You should first define $params as an array and then do it like @mkjasinski said. Also the prepare is done before the complete query build, thus the query that is sent to the Database is:

    SELECT * FROM tbl_name WHERE 1=1

    I believe that doing those two right will get you what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址