matt colley
matt colley

Reputation: 173

mysql_num_rows() Input Validation

I am inserting some values into a mysql database, and before I insert I want to check if one of the input fields has a value that is already in the database before I allow the insert.

When I run the script I get this error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource

and the error points back to this line in my PHP:

if(mysql_num_rows($result) > 0)

Here is the PHP:

$qry = "SELECT * FROM videos WHERE tape_no='$tape_no'";
$result = $dbLink->query($qry) or die (mysql_error());
if($result) {
if(mysql_num_rows($result) > 0) 
{
echo '<html>';
     echo '<head>';
echo '<link href="/module.css" rel="stylesheet type="text/css" />';
echo '</head>';
echo '<body>';
echo '<h1>Error</h1>';
echo '<h3>The Tape Number That You Have Entered is a Duplicate, Please Choose Another Tape Number</h3>';
echo '<FORM><INPUT TYPE="BUTTON" class="bluebutton" VALUE="Go Back" ONCLICK="history.go(-1)"></FORM>';
echo '</body>';
echo '</html>';
}
@mysql_free_result($result);
}

Does the column that I am referencing need to be of a certain data type (ie. Integer) ? Will a varchar column type work here?

Upvotes: 1

Views: 472

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

Introduction

PHP ships with two distinct MySQL-specific API extensions:

  • MySQL, supporting procedural style only (mysql_query());
  • MySQLi, supporting OO style (mysqli::query()) and procedural style (mysqli_query());

  • There are also vendor-nonspecific abstraction layers, such as PDO.


Your problem

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource

Well, it's not one.

if(mysql_num_rows($result) > 0)

expects that $result is a result resource as obtained through the MySQL series of functions.

However, in your code, it's most likely a result from some other extension. Unless you've written some leaky abstraction layer, you're mixing two different extensions!

(You're going to have the same problem with mysql_free_result($result). Read the documentation for whichever extension you're using.)


Your solution

If using MySQLi, try:

if ($result->num_rows > 0)

If using PDO, try:

if ($result->rowCount > 0)

Upvotes: 4

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175017

I think you are mixing 2 different mysql resources. As there is no way that you used

$result = $dbLink->query($qry)

And received a mysql result set (mysql_* doesn't support OOP). Here's how I'd do it in PDO

$query = "SELECT * FROM videos WHERE tape_no='$tape_no'";
$stmt = $db->query($query);
if (!$stmt) { throw new Exception("Query was not complete."); }
if ($stmt->rowCount > 0) {
     //Good Stuff
}

Upvotes: 0

Related Questions