Sahan Jayawardena
Sahan Jayawardena

Reputation: 41

Print array values from select syntax in php

I have a database which have 4 records in it. And I want to display the record details of which having reg_no = "IT17052498" (I'm already having that record in the db). But it gives and error like

"Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\labsheet 10\addcomment.php on line 85"

Database connection are as followed name(db_connect.php)

<?php
$hostname = "localhost";
$username = "root";
$password = "";

$mysql_db = "iwt";

$connection = mysqli_connect($hostname,$username,$password,$mysql_db);
if(!$connection)
{
die("Error : ".mysqli_error($connection));
}

else
{
echo "Successfully Connected!<br>";
}
?>

Here is my php code..

<html>

<body>
<table border="1">
<tr>
<th>Registration Number</th>
<th>Student Name</th>
<th>Comment on ITA</th>
</tr>
<?php
if(isset($_POST["btn_search"]))
$srch = $_POST["search"];
$query = "SELECT * FROM  library_comment WHERE regNo = $srch";

$exst = mysqli_query($connection,$query);
while($row = mysqli_fetch_array($exst))
{

?>

<tr>
<td><?php echo $row['regNo'] ?></td>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['comment'] ?></td>
</tr>

<?php
}

?>


</table>
</body>

Upvotes: 0

Views: 51

Answers (1)

melpomene
melpomene

Reputation: 85767

I don't even use PHP, but the error message says the problem is in the first argument in the call to mysqli_fetch_array():

mysqli_fetch_array($exst)

Specifically, $exst is supposed to be a mysqli_result object, but it's actually a boolean (either true or false).

$exst comes from this line:

$exst = mysqli_query($connection,$query);

http://php.net/mysqli_query says:

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.

In other words, mysqli_query is failing and returning false, and your code doesn't check for errors, it just assumes everything is OK. This is the immediate source of your problem.

On another note, the documentation also says

Data inside the query should be properly escaped.

Your code doesn't escape anything. This might be why the query fails.

Upvotes: 1

Related Questions