简体   繁体   English

如何从mysqli_fetch_array传递查询值?

[英]How can I pass my query values from mysqli_fetch_array?

I am trying to insert values into a table in my database. 我试图将值插入数据库中的表中。 The first param is a non null variable, the next two are the two columns I want to pass in as well. 第一个参数是一个非null变量,接下来的两个是我也想传递的两列。 What is wrong with my logic here. 我在这里的逻辑出了什么问题。

$query  = "SELECT cnum, cname FROM course WHERE specialization = '0'";  
 $result = mysqli_query($conn,$query);

 if (!$result) die ("Database access failed: " . $conn->error);

 $rows = $result->num_rows;    
for ($j =0; $j<$rows;++$j) {

     $row = mysqli_fetch_array($result);
     $query = "INSERT INTO student_schedule VALUES ('$studentID', '$row[0]', '$row[1]', '0')";

     $result = $conn->query($query);
     if (!$result) die ("Database access failed: " . $conn->error);

 }

Your solution 您的解决方案

<?php
$query  = "SELECT cnum, cname FROM course WHERE specialization = '0'";  
$result = mysqli_query($conn,$query);
if (!$result) die ("Database access failed: " . $conn->error);

while ($row = mysqli_fetch_array($result)) {
    $insertQuery = "INSERT INTO student_schedule VALUES ('" . $conn->real_escape_string($studentID) . "', '" . $conn->real_escape_string($row[0]) . "', '" . $conn->real_escape_string($row[1]) . "', '0')");
    $insert = $conn->query($insertQuery);
    if (!$result) die ("Database access failed: " . $conn->error);
}
?>

Also, as a general rule, I suggest you don't mix MySQLi Procedural code with Object-Oriented code. 另外,作为一般规则,我建议您不要将MySQLi过程代码与面向对象的代码混合使用。 Lastly, I also suggest you remove error outputting $conn->error , instead, capture the error and print out a custom error message instead. 最后,我还建议您删除输出$conn->error ,而是捕获错误并打印出自定义错误消息。 This reduces injection attacks. 这样可以减少注入攻击。

Your code is vulnerable to SQL Injections , that might to be the reason why it doesn't work properly. 您的代码容易受到SQL注入的攻击,这可能就是为什么它无法正常工作的原因。

You should escape the data before including it into an SQL query: 在将数据包含到SQL查询中之前,应先对其进行转义:

for ($j =0; $j<$rows;++$j) {

    $row = mysqli_fetch_array($result);
    $query = $conn->prepare("INSERT INTO student_schedule VALUES (?, ?, ?, '0')";
    $query->bind_param('iss', $studentID, $row[0], $row[1]);
    $result = $query->execute();
    if (!$result) die ("Database access failed: " . $conn->error);

}

You can find more information on the bind_param() function in the PHP manual . 您可以在PHP手册中找到关于bind_param()函数的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM