【问题标题】:How can I write a query for each element of json_decode?如何为 json_decode 的每个元素编写查询?
【发布时间】:2016-10-11 21:49:13
【问题描述】:

我在 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 解码的每个元素编写一个查询,但它不起作用。

【问题讨论】:

    标签: php android mysql json


    【解决方案1】:

    一个可能的解决方案(如果我理解正确的话):

    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 (implode(', ', $list))";
    

    【讨论】:

      【解决方案2】:

      您可以使用 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
      
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多