I wrote this code to retrieve some data from data base But the code do not display the first value in the table which is started from second row. How I can make this code retrieve the data from first row.
<html>
<head>
<title>hello</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"uoh");
$q = " SELECT * FROM student_record WHERE id =201102887;";
$result = mysqli_query($con , $q ) ;
if($row = mysqli_fetch_array($result)) {
echo "<table border=\"1\" style=\"width:500\">";
echo "<tr>";
echo "<th>courses</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
Change
if($row = mysqli_fetch_array($result)) {
to
if(mysqli_num_rows($result) > 0) {
Updated Code
<html>
<head>
<title>hello</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"uoh");
$q = " SELECT * FROM student_record WHERE id =201102887;";
$result = mysqli_query($con , $q ) ;
if(mysqli_num_rows($result)>0) {
echo "<table border=\"1\" style=\"width:500\">";
echo "<tr>";
echo "<th>courses</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
You are calling mysqli_fetch_array two times second call is going to the second row. Try like this
<html>
<head>
<title>hello</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"uoh");
$q = " SELECT * FROM student_record WHERE id =201102887;";
$result = mysqli_query($con , $q ) ;
$rows = array();
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
if(count($rows) > 0) {
echo "<table border=\"1\" style=\"width:500\">";
echo "<tr>";
echo "<th>courses</th>";
echo "</tr>";
foreach($rows as $row)
{
echo "<tr>";
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
as far as i know when you call this twice,
if($row = mysqli_fetch_array($result)) {
then first row will skip when you call it again in loop, what point you create if($row = mysqli_fetch_array($result)) {
? if you just want check query return you can just use if($result) {