如何将数组数据用于查询以获取PHP

时间:2016-05-01 16:49:31

标签: php mysql arrays database

所以这是我的PHP代码:

$checkProject1Column = "SELECT * FROM tbl_studentchoice WHERE Project1 = '1'";
$resultProject1Column = mysqli_query($conn, $checkProject1Column);       
    while($row = mysqli_fetch_assoc($resultProject1Column)) {
            //Create an array of students
            $array[] = ['studentid' => $row['studentid']];
    }  
    //check marks database
    $checkmarks = "SELECT studentid,marks FROM tbl_marks";
    $checkResult = mysqli_query($conn, $checkmarks);
    if ($checkResult->num_rows >= 0){
        while($row1 = mysqli_fetch_assoc($checkResult)){
            //Create an array of students
            $array1[] = [
                'marks' => $row1['marks'],
                'studentid' => $row1['studentid']
                ];
            }
        print_r($array);
        print_r($array1);

所以我有2个数据库表。 tbl_studentchoicetbl_marks。 我在Project1列上创建了一个值为1的学生数组。这就是我的tbl_studentchoice的样子:

projtbl

所以现在我有了一系列的学生。我想从另一张表(tbl_marks)中得到这些学生的分数,如下所示:

marks

并创建一个仅包含studentid Project1值为1的新数组及其标记。所以基本上我想创建一个这样的数组:

Array ( 
    [0] => Array ( 
        [studentid] => c12558111 
        [marks] => 50
    ) 
    [1] => Array ( 
        [studentid] => c12558112 
        [marks] => 60
    ) 
)

1 个答案:

答案 0 :(得分:4)

为什么你使用两个不同的查询? 你应该连接表只写一个这样的查询

select s.*,m.marks
  from tbl_studentchoice s, tbl_marks m
  where s.studentid = m.studentid
   and  Project1 = '1'

完整代码

$query= "select s.*,m.marks
  from tbl_studentchoice s, tbl_marks m
  where s.studentid = m.studentid
   and  Project1 = '1'";
$result= mysqli_query($conn, $query);       
while($row = mysqli_fetch_assoc($result)) {

  echo("<br/>Student ID = ".$row['studentid']);
  echo("<br/>Student marks = ".$row['marks']);
}