【问题标题】:How to use array data into query to get another data in PHP如何在查询中使用数组数据来获取 PHP 中的另一个数据
【发布时间】:2016-05-01 16:49:30
【问题描述】:

这是我的 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 的样子:

所以现在我有了一个学生 ID 数组。我想从另一个表格 (tbl_marks) 中获取这些学生的分数,如下所示:

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

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

【问题讨论】:

  • 重复$resultProject1Column = mysqli_query($conn, $checkProject1Column); 有什么原因吗?
  • 其实不让我编辑我的代码

标签: php mysql arrays database


【解决方案1】:

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

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']);
}

【讨论】:

  • 非常感谢。我仍然没有足够的 PHP 经验,所以我不知道你可以做这样的查询。你能向我解释一下我不完全理解的问题。我已经完成并创建了数组及其好处。我只是想进一步了解该查询。
  • 这就像一个内部连接,它以某种条件连接两个表,在你的问题中,有两个表有一个公共列是 studentid,所以这个查询将合并两个表的数据,其学生 ID 相同
猜你喜欢
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 2019-04-02
  • 1970-01-01
  • 2019-10-04
  • 2015-10-20
  • 2020-09-11
  • 2018-02-15
相关资源
最近更新 更多