gpt4 book ai didi

php - 如何为 json_decode 的每个元素编写查询?

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:23 24 4
gpt4 key购买 nike

我从 Android 中的 volley 请求中将一个 JSON 数组作为字符串发布,并使用 JSON 解码对其进行解码。这是我的 PHP 代码:

 if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$courseList = $_POST['courseList'];

$professor_ID = $_POST['Prof_ID'];

$list = json_decode($courseList);

print_r($list);
require_once('dbConnect.php');

$sql = "select Stud_ID,student.f_Name,student.l_Name from student,course where course.S_ID = student.Stud_ID and course.P_ID in ($list)";
.
.
.
?>

这里是 print_r($list) 结果:

 Array
(
[0] => 1
[1] => 2
)

现在,我想为 JSON 解码的每个元素编写一个查询,但它不起作用。

最佳答案

您可以使用 foreach 循环或内爆

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
require_once('dbConnect.php');
// i am assuming $con is your connection variable

// its good practice to check against sql injection
$courseList = mysqli_real_escape_string( $con, $_POST['courseList'] );
$professor_ID = mysqli_real_escape_string( $con, $_POST['Prof_ID'] );

$list = json_decode( $courseList );

print_r( $list );

// Assuming $list is
// Array
// (
// [0] => 1
// [1] => 2
// )

foreach ( $list as $p_id ) {
// prepare your query
$sql = "select Stud_ID,student.f_Name,student.l_Name from student,course where course.S_ID = student.Stud_ID and course.P_ID = $p_id ";
// execute and do other stuff
}

// or use implode
$pid = (implode(', ', $list);
$sql = "select Stud_ID,student.f_Name,student.l_Name from student,course where course.S_ID = student.Stud_ID and course.P_ID in $pid ";
// execute and do other stuff


?>

关于php - 如何为 json_decode 的每个元素编写查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37756499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com