函数,使用mysqli_fetch_array输出数据库记录


function using mysqli_fetch_array to output database records

我仍在学习函数,有点不确定。

我这里有这个代码:

<?php
include ('blah.html');
$conn = mysqli_connect("localhost","root","","testing");
// Check connection
if (mysqli_connect_errno())
{
    echo "<p>Failed to connect to MySQL: " . mysqli_connect_error() . "</p>";
}
else
{
    echo "<p>Connected to mysql and the testing database</p>";
}
/*function produceTable(){
    $result = mysqli_query($conn,"SELECT studentid, CONCAT(firstname,' ', lastname) as name,phone, email, courseid FROM students WHERE courseid > 1500 ORDER BY lastname");
    return $result;
}*/
$result = mysqli_query($conn,"SELECT studentid, CONCAT(firstname,' ', lastname) as name,phone, email, courseid FROM students WHERE courseid > 1500 ORDER BY lastname");
$numRecords = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td align = 'center'>".$row['studentid']."</td>";
    echo "<td>".$row['name']."</td>";
    echo "<td>".$row['phone']."</td>";
    echo "<td>".$row['email']."</td>";
    echo "<td>".$row['courseid']."</td>";
    echo "</tr>";
}
echo "</table>";
echo "<p>".$numRecords." records found with course id larger than 1500</p>";                    
?>
</body>
</html>

正如你所看到的,我已经把函数注释掉了。如果你忽略这个函数,这个代码会工作并输出我想要的记录,但我需要能够使它与一个函数一起工作。该函数需要被调用produceTable()并接受一个名为$result的参数。它还需要使用mysqli_fetch_array()来输出记录。

在您的produceTable()中,$conn就是undefined。只需传递$conn作为参数。像这个

function produceTable($conn){
    $result = mysqli_query($conn,"SELECT studentid, CONCAT(firstname,' ', lastname) as name,phone, email, courseid FROM students WHERE courseid > 1500 ORDER BY lastname");
    return $result;
}
$result = produceTable($conn);
$numRecords = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)) {
    .....
}

您的下一个功能是:

function produceTable(){
    $result = mysqli_query($conn, "SELECT ...");
    return $result;
}

$conn没有值。不是吗?尝试将此参数传递给函数