javascript - 将 js 数组发布到 PHP 并在数据库查询中使用它
问题描述
我希望我的 javascript 函数将多个变量传递给 PHP,然后让 PHP 在 select 语句中使用这些变量。目前,当我只传递字符串变量时,我的代码就可以工作,但是只要我将这一行添加AND newVar IN ('+$myVarArrayPHP+')
到查询中,查询就不会从数据库中提取任何内容(肯定有一行与查询匹配的数据)。非常感谢!!
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:
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);
}
}
解决方案
您需要告诉 PHP 如何处理数组,例如通过使用implode
(PHP 文档):
//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);
转换["grape", "mango", "apple"]
为字符串:grape,mango,apple
. 现在 SQL 能够处理它。
pg_prepare()
准备好的语句的文档: PHP 文档
编辑
- 我错过
"
了数组的索引 implode()
是正确的想法,但我将它用于错误的事情,因为它会生成"grape, mango, apple"
,因此您的数据库将完全查找此字符串。相反,我们需要寻找"grape", "mango", "apple"
.- 使用
splat
PHP的运算符$myVarArrayPHP
动态反汇编。
灵感来自https://supunkavinda.blog/php-mysqli-prepared-where-in。
2ND EDIT
由线程开启者回答另一个问题,以根据count($results)
先前的语句执行多个查询。
推荐阅读
- ios - xcode9 swift4 致命错误:在展开可选值时意外发现 nil
- css - 如何在不影响其他元素的情况下设置特定输入类型元素的样式
- sql - 如果时间戳介于同一人的其他 2 个时间戳之间以进行另一次预订
- python - 选择不在范围之间的列表中的随机整数
- c# - 值不能为空。参数名称:first
- c# - Unity c#图像未出现在UI画布面板中
- java-8 - 给定带有 getOrDefault 的键,更新 hashmap 值
- python - Find a value in a list of dicts
- javascript - 将php数组获取到javascript:变量未定义
- mysql - Django:切换到 MySQL 后连接被拒绝