Fetch_array errors when querying data with mysqli_query
If I try to create a sql query like:
$sql2 = mysqli_query($connection,"SELECT * FROM CHILD_IMG WHERE PROD_ID='$delID'") or die(mysqli_error());
$getQuery = $connection->query($sql2);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = '../ProductImages/ChildImages/'.$parentID . "_".$childID.".jpg";
unlink($childName);
}
I am getting the following error:
Fatal error: Calling member function fetch_array () at zero in
If I run and save the query before $sql
like this:
$sql2 = ("SELECT * FROM CHILD_IMG WHERE PROD_ID = '$delID'") or die(mysqli_error());
$getQuery = $connection->query($sql2);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = '../ProductImages/ChildImages/'.$parentID . "_".$childID.".jpg";
unlink($childName);
}
The request runs smoothly.
What is the problem, why does the first option not work?
source to share
See this bit of code?
$sql2 = mysqli_query($connection,"SELECT * FROM CHILD_IMG WHERE PROD_ID='$delID'") or die(mysqli_error());
^^^^^^^^^^^^
$getQuery = $connection->query($sql2);
^^^^^
You are actually asking twice why you are getting the error.
Also or die(mysqli_error())
owned after the request call and this requires a db connection.
Ie of: or die(mysqli_error($connection))
.
So, you have to do the following to check if the request failed:
if(!$getQuery){
echo "Error: " . die(mysqli_error($connection));
}
Rewrite:
$sql2 = "SELECT * FROM CHILD_IMG WHERE PROD_ID='$delID'";
$getQuery = $connection->query($sql2);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = '../ProductImages/ChildImages/'.$parentID . "_".$childID.".jpg";
unlink($childName);
}
You are also open to SQL injection; use a prepared statement.
Literature:
- https://en.wikipedia.org/wiki/Prepared_statement
- http://php.net/manual/en/mysqli.prepare.php (mysqli)
- http://php.net/manual/en/pdo.prepared-statements.php (PDO)
Note. If you are going to work with PDO, remember to mix the various MySQL APIs.
source to share