Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/im2db/image.php on line 14

This is the error I am getting

Here is the code:
Image.php
Am I supposed to add a exit(); after
$result = mysql_query ($sql, $conn);
line?

<?php
// database connection
$conn = mysql_connect("localhost", "user", "pass") OR DIE (mysql_error());
@mysql_select_db ("user_images", $conn) OR DIE (mysql_error());
$sql    = "SELECT * FROM images WHERE image_id=".$_GET["iid"]; 

$result = mysql_query ($sql, $conn);

if (mysql_num_rows ($result)>0) {
  $row = @mysql_fetch_array ($result) or die (mysql_error());
  $image_type = $row["image_type"];
  $image = $row["image"];
  Header ("Content-type: $image_type");
  print $image;
}
?>

Warning: fread(): supplied argument is not a valid stream resource in /home/user/public_html/im2db/index.php on line 18
This is the error I get when I submit a blank entry.

<?php
// index.php - by Hermawan Haryanto <hermawan@dmonster.com>
// Example PHP Script, demonstrating Storing Image in Database
// Detailed Information can be found at http://www.codewalkers.com

// database connection
$conn = mysql_connect("localhost", "user", "pass") OR DIE (mysql_error());
@mysql_select_db ("user_images", $conn) OR DIE (mysql_error());

// Do this process if user has browse the file and click the submit button
if ($_FILES) {
  $image_types = Array ("image/bmp",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/gif",
                        "image/x-png");

  $userfile  = addslashes (fread (fopen ($_FILES["userfile"]["tmp_name"], "r"), filesize ($_FILES["userfile"]["tmp_name"])));
  $file_name = $_FILES["userfile"]["name"];
  $file_size = $_FILES["userfile"]["size"];
  $file_type = $_FILES["userfile"]["type"];

  if (in_array (strtolower ($file_type), $image_types)) {
    $sql = "INSERT INTO images (image_type, image, image_size, image_name, image_date) ";
    $sql.= "VALUES (";
    $sql.= "'{$file_type}', '{$userfile}', '{$file_size}', '{$file_name}', NOW())";
    @mysql_query ($sql, $conn);
    Header("Location:".$_SERVER["PHP_SELF"]);
    exit();
  }
}

// Do this process of user has click a file name to view or remove
if ($_GET) {
  $iid = $_GET["iid"];
  $act = $_GET["act"];
  switch ($act) {
    case rem:
      $sql = "DELETE FROM images WHERE image_id=$iid";
      @mysql_query ($sql, $conn);
      Header("Location:./index.php");
      exit();
      break;
    default:
      print "<img src=\"image.php?iid=$iid\">";
      break;
  }
}

?>
<html>
<head>
<title>Storing Images in DB</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Select Image File: <input type="file" name="userfile"  size="40"><input type="submit" value="submit">
</form>
<?php
  $sql = "SELECT * FROM images ORDER BY image_date DESC";
  $result = mysql_query ($sql, $conn);
  if (mysql_num_rows($result)>0) {
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
      $i++;
      $str .= $i.". ";
      $str .= "<a href=\"index.php?iid=".$row["image_id"]."\">".$row["image_name"]."</a> ";
      $str .= "[".$row["image_date"]."] ";
      $str .= "[".$row["image_size"]."] ";
      $str .= "[<a href=\"index.php?act=rem&iid=".$row["image_id"]."\">Remove</a>]<br>";
    }
    print $str;
  }
?>
</body>
</html>

Dani AI

Generated

Short diagnosis and quick fixes

The warning "mysql_num_rows(): supplied argument is not a valid MySQL result resource" means mysql_query() returned FALSE instead of a result resource. That happens when the SQL fails (syntax, missing parameter) or the query errors out. In this thread the generated query lacks a valid id, so the query fails. As recommended, echoing the SQL and running it in your database tool is a good first step. Avoid the @ error-suppression operator — it hides the real error. Always validate input (make sure an iid exists and is numeric) and check the query return before calling mysql_num_rows().

A safer, modern pattern (use mysqli or PDO in current PHP) is to validate the id, use a prepared statement, then check results. Example (mysqli):

$iid = isset($_GET['iid']) && ctype_digit($_GET['iid']) ? (int)$_GET['iid'] : 0;
if ($iid <= 0) { http_response_code(400); exit; }

$stmt = $mysqli->prepare('SELECT image_type, image FROM images WHERE image_id = ?');
$stmt->bind_param('i', $iid);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows === 0) { http_response_code(404); exit; }
$stmt->bind_result($type, $blob);
$stmt->fetch();
header("Content-Type: $type");
echo $blob;

About the fread() warning

That error means fopen() returned FALSE (no stream). When a form is submitted without a file, or the upload failed (exceeded upload_max_filesize, post_max_size, or other PHP error), the temporary name will be missing. Check $_FILES['userfile']['error'] === UPLOAD_ERR_OK (do not rely on if($_FILES) alone), use is_uploaded_file() before opening, and prefer move_uploaded_file() for handling uploads. Also verify the HTML form has enctype="multipart/form-data".

Final checklist (quick)

  • Validate $_GET['iid'] before building SQL.
  • Check query return and use mysql_error() (or mysqli error) instead of @.
  • Check $_FILES['userfile']['error'] and PHP upload limits.
  • Consider migrating from old mysql_* to mysqli or PDO and store blobs with prepared statements (or store files on disk and save paths in DB).

These steps combine 's baby-steps debugging and 's suggestion to guard before using mysql_num_rows() and will stop both warnings.

Recommended Answers

All 4 Replies

For your mysql error, test your SQL statement. Right after your line that builds your SQL statement, do this:

echo $sql;
exit();

Examine the output to see if something is wrong with the SQL statement. Try running it directly against your database using phpMyAdmin or the command line client.

For your fopen error, as you know, it happens when you submit a blank form. Yet, the code says "Oh, a form was submitted, let's open the file the user uploaded." But you didn't select a file--you submitted a blank form. SO...you need to add some code to test the validity of the form. Change your "if ($_FILES) {" line with this:

if ($_FILES['userfile']['error'] == 0) {

I do not get "Try running it directly against your database using phpMyAdmin or the command line client."
When I add
if ($_FILES == 0) {
I get:
Warning: fread(): supplied argument is not a valid stream resource in /home/user/public_html/im2db/index.php on line 19
as an error but now it is visible once I go on the index page.
Plus the image does not show up, only as a red x

<?php
// database connection
$conn = mysql_connect("localhost", "user", "pass") OR DIE (mysql_error());
@mysql_select_db ("user_images", $conn) OR DIE (mysql_error());

// Do this process if user has browse the file and click the submit button
if ($_FILES['userfile']['error'] == 0) { 

  $image_types = Array ("image/bmp",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/gif",
                        "image/x-png");

  $userfile  = addslashes (fread (fopen ($_FILES["userfile"]["tmp_name"], "r"), 

filesize ($_FILES["userfile"]["tmp_name"])));
  $file_name = $_FILES["userfile"]["name"];
  $file_size = $_FILES["userfile"]["size"];
  $file_type = $_FILES["userfile"]["type"];

  if (in_array (strtolower ($file_type), $image_types)) {
    $sql = "INSERT INTO images (image_type, image, image_size, image_name, image_date) 

";
    $sql.= "VALUES (";
    $sql.= "'{$file_type}', '{$userfile}', '{$file_size}', '{$file_name}', NOW())";
    @mysql_query ($sql, $conn);
    Header("Location:".$_SERVER["PHP_SELF"]);
    exit();
  }
}

// Do this process of user has click a file name to view or remove
if ($_GET) {
  $iid = $_GET["iid"];
  $act = $_GET["act"];
  switch ($act) {
    case rem:
      $sql = "DELETE FROM images WHERE image_id=$iid";
      @mysql_query ($sql, $conn);
      Header("Location:./index.php");
      exit();
      break;
    default:
      print "<img src=\"image.php?iid=$iid\">";
      break;
  }
}

?>
<html>
<head>
<title>Storing Images in DB</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Select Image File: <input type="file" name="userfile"  size="40"><input type="submit" 

value="submit">
</form>
<?php
  $sql = "SELECT * FROM images ORDER BY image_date DESC";
  $result = mysql_query ($sql, $conn);
  if (mysql_num_rows($result)>0) {
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
      $i++;
      $str .= $i.". ";
      $str .= "<a href=\"index.php?iid=".$row["image_id"]."\">".$row

["image_name"]."</a> ";
      $str .= "[".$row["image_date"]."] ";
      $str .= "[".$row["image_size"]."] ";
      $str .= "[<a href=\"index.php?act=rem&iid=".$row["image_id"]."\">Remove</a>]

<br>";
    }
    print $str;
  }
?>
</body>
</html>

with images.php as a result: SELECT * FROM images WHERE image_id=
when I go to the page.

<?php

// database connection
$conn = mysql_connect("localhost", "user", "pass") OR DIE (mysql_error());
@mysql_select_db ("user_images", $conn) OR DIE (mysql_error());
$sql    = "SELECT * FROM images WHERE image_id=".$_GET["iid"]; 

$result = mysql_query ($sql, $conn);
echo $sql;
exit(); 
if (mysql_num_rows ($result)>0)

 {
  $row = @mysql_fetch_array ($result) or die (mysql_error());
  $image_type = $row["image_type"];
  $image = $row["image"];
  Header ("Content-type: $image_type");
  print $image;

}
?>

Thank you a lot for helping me a lot though =O.

Troubleshooting 101
When troubleshooting code problems, the secret is baby-steps. When you have an error, it is always a single statement (or line) that is producing the error. Create a new file, and put in only enough code to produce your problem, then work until you solve it--one line at a time. Baby-steps.

In keeping with the baby-steps philosophy, let's attack only one problem at a time. Let's look at your SQL problem. Create a new file with only this code:

$conn = mysql_connect("localhost", "user", "pass") OR DIE (mysql_error()); 
@mysql_select_db ("user_images", $conn) OR DIE (mysql_error()); 

$sql	= "SELECT * FROM images WHERE image_id=".$_GET["iid"]; 
echo $sql; 

if (!$result = mysql_query ($sql, $conn)) {
  echo mysql_error();
} else {
  echo "<br />query successful";
}

Now, call this script directly within your browser using a URL such as

The script should display in your browser the SQL statement that it runs against the database. Examine that statement--do you see anything wrong with it? If not, then copy the statement from your browser window and run it directly against your database. What I mean by that is if you are working with a database, you must have some tool you use to create your tables--right? For many people with MySql, that tool is phpMyAdmin. Do you have access to use phpMyAdmin? If not, whatever tool you use to manage you database, should have a way to paste in a query and execute it. This way you can test that the SQL statement you are generating in your PHP code is actually a valid statement that your database can execute. Maybe it is a valid statement, but it does not return any rows because no rows match the query.

Once you work through this part, you can add more steps---one at a time--baby steps--until you have the whole script working.

always make a test condition before using
mysql_num_rows()
because if the table is empty so the process is stopped

$array[]=@mysql_num_rows(elements functions);

if (count($array)==0) //ur table is empty

that's all!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.