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

xu3bshqb  于 2023-04-28  发布在  Mysql
关注(0)|答案(2)|浏览(124)

我在Android中发布了一个JSON数组作为一个字符串,并使用JSON decode对其进行解码。下面是我的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解码的每个元素编写一个查询,但它不起作用。

bkkx9g8r

bkkx9g8r1#

可以使用foreach循环或implode

<?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

?>
mcvgt66p

mcvgt66p2#

在这个代码片段中,我使用inflode函数将$list数组转换为逗号分隔的字符串,然后将其与SQL查询字符串连接起来。这应该可以正确地与您的SQL查询一起工作。

$implodedList = 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 ($implodedList)";

相关问题