duano3557 2016-07-11 01:00
浏览 56
已采纳

PHP PDO发布字符串列表IN Where子句

I almost have the following code working, but unfamiliar with how to post my list from enduser to $ids in array form like my test. The end user would send a list to me as "3,5,7,8...)

How do I simulate "$ids = array(1,2,3)" when converting to a POST statement?

<?php
//1. Create a database connection

require_once('config.php');
    $mysql_host = DB_HOST;
    $mysql_database = DB_NAME;
    $mysql_username = DB_USER;
    $mysql_password = DB_PASS;

$ids = $_POST["idsvar"]; //Doesn't return values
//$ids =  array(1,2,3); //This does work when used for testing purposes

$inQuery = implode(',', array_fill(0, count($ids), '?'));


try {
    $conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

    //2. Perform database query if Connected Successfully
    $stm = $conn ->prepare(
    'SELECT `schema`.`table`.`column1` AS `DiffNameA`,
    `schema`.`table`.`column2` AS `DiffNameB`
     FROM `schema`.`table`
     WHERE id IN(' . $inQuery . ')');

foreach ($ids as $k => $id)
    $stm->bindValue(($k+1), $id);
    $stm->execute();

$field = $stm->fetchAll();

foreach ($field as $row) {
print $row["DiffNameA"] . "|" .$row["DiffNameB"] ."
"; //extra comma so can have notes hidden area
}   

  $conn = null;        // Disconnect    
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage().'<br />';
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    }
?>

Thank you for any help.

===============================================================

In case it helps anyone, this is the complete script:

<?php
//1. Create a database connection

require_once('config.php');
    $mysql_host = DB_HOST;
    $mysql_database = DB_NAME;
    $mysql_username = DB_USER;
    $mysql_password = DB_PASS;



$ids = explode(',', $_POST["idsvar"]);
$inQuery = implode(',', array_fill(0, count($ids), '?'));


try {


    $conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

    //2. Perform database query if Connected Successfully
    $stm = $conn ->prepare(
    'SELECT `schema`.`table`.`column1` AS `DiffNameA`,
    `schema`.`table`.`column2` AS `DiffNameB`
     FROM `schema`.`table`
     WHERE id IN(' . $inQuery . ')');

foreach ($ids as $k => $id)
    $stm->bindValue(($k+1), $id);
    $stm->execute();

$field = $stm->fetchAll();

foreach ($field as $row) {
print $row["DiffNameA"] . "|" .$row["DiffNameB"] ."
"; //extra comma so can have notes hidden area
}


  $conn = null;        // Disconnect    
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage().'<br />';
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    }
?>
  • 写回答

1条回答 默认 最新

  • duanmu2015 2016-07-11 01:15
    关注

    Your $_POST["idsvar"] is a string, not an array. Use explode to split it to an array at each comma.

    $test = explode(',', '1,2,3');
    

    Demo: https://eval.in/603133

    In your case:

    $ids = explode(',', $_POST["idsvar"]);
    

    The count($ids) works in your static example because you defined $ids as an array ($ids = array(1,2,3)).

    or if you wanted to validate the input as well you could use a regex.

    (\d+)(?:,|\z)
    

    https://regex101.com/r/dI5fN4/1

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

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊