Murph_Fish Murph_Fish - 7 months ago 17
PHP Question

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. 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);

}

Answer

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 ('" . $studentID . "', '" . $row[0] . "', '" . $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. Lastly, I also suggest you remove error outputting $conn->error, instead, capture the error and print out a custom error message instead. This reduces injection attacks.

Comments