简体   繁体   English

将 js 数组发布到 PHP 并在数据库查询中使用它

[英]Posting a js array to PHP and using it in a database query

I want my javascript function to pass multiple variables down to PHP and then have PHP use those variables in a select statement.我希望我的 javascript 函数将多个变量传递给 PHP,然后让 PHP 在 select 语句中使用这些变量。 Currently my code works when I just pass the variables that are strings but as soon as I added this line: AND newVar IN ('+$myVarArrayPHP+') into the query, the query doesn't pull anything from the database(There definitely is a row of data that matches the query).目前,当我只传递字符串变量时,我的代码可以工作,但是只要我添加了这一行: AND newVar IN ('+$myVarArrayPHP+')到查询中,查询就不会从数据库中提取任何内容(肯定有与查询匹配的一行数据)。 Thanks so much!!非常感谢!!

JS: JS:

var varSring1= "test";
var varString2= "testing";
var varArray= [""] // the number of elements in the array is determined dynamically and are all strings for example: ["grape","mango","apple"]
$.ajax({
   type: 'POST',
   url: "myPHPFile.php",
   data: {
       myVar1: varSring1,
       myVar2: varString2,
       myVarArray: varArray
     },
   dataType: "json",
   success: function (response)
       if ((response[0]['var1']) != null) {
       document.getElementById("tc-unique-ID-1").value = (response[0]['var1']);}

      if ((response[0]['var2']) != null) {
      document.getElementById("tc-unique-ID-2").value = (response[0]['var2']);}
   error: function (err) {
            console.error(err.responseText);
        }
    });


}

PHP: PHP:


if(isset($_POST[myVar1]) && ($_POST[myVar2]) && ($_POST[myVarArray])){  //check if $_POST[''] exists
  $myVar1PHP= $_POST[myVar1];
  $myVar2PHP= $_POST[myVar2]; 
  $myVarArrayPHP= $_POST[myVarArray]; 

  $ret = pg_query($connection, "SELECT * FROM table 
  WHERE  var1= '$myVar1PHP' AND var2= '$myVar2PHP' AND newVar IN ('+$myVarArrayPHP+');")

  $results=array();
  while($row = pg_fetch_assoc($ret) ){
    array_push( $results,$row);
  }  


}

You need to tell PHP how to deal with the array, eg by using implode ( PHP documentation ):您需要告诉 PHP 如何处理数组,例如使用内implodePHP 文档):

//check if $_POST['...'] exists
if(isset($_POST["myVar1"]) && isset($_POST["myVar2"]) && isset($_POST["myVarArray"]) && isset($_POST["differentPostedVar"]) && isset($_POST["lastPostedVar"])){
    $myVar1PHP= $_POST["myVar1"];
    $myVar2PHP= $_POST["myVar2"]; 
    $myVarArrayPHP= $_POST["myVarArray"];
    $differentPostedVar = $_POST["differentPostedVar"]; // assumption
    $lastPostedVar = $_POST["lastPostedVar"];

    // newVar IN ($3, $4, $5); and so on
    $first_sql = "SELECT * FROM table WHERE  var1= $1 AND var2= $2 AND newVar IN (put_placeholders_here);";
    $results = execute_prepared_statement($connection, $first_sql, "first_sql", array($myVar1PHP, $myVar2PHP), $myVarArrayPHP);

    if(0 == count($results)) {
        $second_sql = "SELECT * FROM table WHERE differentVar= $1 AND var2= $2 AND newVar IN (put_placeholders_here);";
        $results = execute_prepared_statement($connection, $second_sql, "second_sql", array($differentPostedVar, $myVar2PHP), $myVarArrayPHP);

        if(0 == count($results)) {
            $third_sql = "SELECT * FROM table WHERE 3rdQ= $lastPostedVar;";
            $results = execute_prepared_statement($connection, $third_sql, "third_sql", array($differentPostedVar, $myVar2PHP), $myVarArrayPHP);
        }
    }

    echo json_encode($results);
}

function execute_prepared_statement($connection, $sql, $query_name, $normal_params, $in_array = null) {
    $elementsCount = count($in_array);
    $no_of_other_params = count($normal_params); // you need to start with $3 because of $myVar1PHP and $myVar2PHP

    // generate an array that holds a placeholder ($3, $4 etc.) for every value in $myVarArrayPHP
    $binding_placeholders = array();
    for($i = 0; $i < $elementsCount; $i++) {
        $binding_placeholders[] = "$" . ($i + $no_of_other_params + 1);
    }

    // array to string conversion (will produce "$3,$4,$5" etc.)
    $placeholders = implode(",", $binding_placeholders);
    // replace placeholder string with actual placeholder string 
    $sql = str_replace('put_placeholders_here', $placeholders, $sql);

    $ret = pg_prepare($connection, $query_name, $sql);

    // using array_merge to create one array having all parameters
    $parameters = array_merge($normal_params, $in_array); 

    $result = pg_execute($connection, $query_name, $parameters);

    $results=array();

    while($row = pg_fetch_assoc($ret) ){
        array_push( $results, $row );
    }

    return $results;
}

implode(',', $array); converts ["grape", "mango", "apple"] to a string: grape,mango,apple .["grape", "mango", "apple"]转换为字符串: grape,mango,apple Now SQL is able to deal with it.现在 SQL 能够处理它。

Documentation for the pg_prepare() prepared statement: PHP Documentation pg_prepare()准备语句的文档PHP 文档

EDIT编辑

  1. I was missing the " around the indices of the arrays我错过了数组索引周围的"
  2. implode() was the right idea but I used it for the wrong thing because it will generate "grape, mango, apple" so your database will look exactly for this string. implode()是正确的想法,但我将它用于错误的事情,因为它会生成"grape, mango, apple"因此您的数据库将准确查找此字符串。 Instead, we need to look for "grape", "mango", "apple" .相反,我们需要寻找"grape", "mango", "apple"
  3. Using thesplat operator of PHP to disassemble $myVarArrayPHP dynamically.使用 PHP 的splat运算符动态反汇编$myVarArrayPHP

Inspiration from https://supunkavinda.blog/php-mysqli-prepared-where-in .灵感来自https://supunkavinda.blog/php-mysqli-prepared-where-in

2ND EDIT Answer to another question by thread opener to execute several queries based on count($results) of previous statements.第二个编辑回答线程开启者的另一个问题,以根据先前语句的count($results)执行多个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM