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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?