PHP - Issue With Mysql_num_rows
I am having trouble calling mysql_num_rows in my script. I get the error message "PHP Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\scripts\update.php on line 41". I have looked around online but can only find the my sql is not right. I am able to copy and past the sql into mysql workbench and it runs fine. Any help would be much appreciated.
Code: [Select] $game_id = $row['id']; $game_name = $row['game_name']; print("updating game {$game_id}: {$game_name}" . PHP_EOL); $sql = "SELECT users.id, users.username, users.number_attended_games FROM users join game_sessions_users on game_sessions_users.user_id = users.id where game_sessions_users.game_session_id = " . $game_id; print($sql . PHP_EOL); $players = mysql_query($sql, $connection) or die(mysql_error($connection));; if(mysql_num_rows($players >= 1)){ while($player = mysql_fetch_array($players, MYSQL_ASSOC)){ print('updating player: ' . $player['username']); $number_attended_games = $player['number_attended_games']; $user_id = $player['id']; $sql = "UPDATE users SET number_attended_games = " . ($number_attended_games + 1) . ", user_level = " . ($number_attended_games / 10) . " WHERE id = " . $user_id; $update_result = mysql_query($sql, $connection); } } $sql = "UPDATE game_sessions SET completed = 1 WHERE id = " . $game_id; $update_result = mysql_query($sql, $connection); Similar TutorialsHi I am trying to create a login script using the code below Code: [Select] <?php session_start(); include_once('includes/connect.php'); $user=$_POST['username']; $password=$_POST['password']; //check if username and password exists $checkuser=mysql_query("SELECT * from `tbl_users` where username = '$user' and password=md5('$password')"); if(mysql_num_rows($checkuser) > 0) //login name was found //if they do return to home page with relevant include { $user_row = mysql_fetch_array($checkuser); $_SESSION['auth']="yes"; $_SESSION['logname'] = $user_row['forename']; $_SESSION['usertype'] = $user_row['usertype']; header("Location: index.php"); exit; } //if not display login form with message that says logon details are incorrects else { echo('Do something else'); } ?> However I get a message saying that mysql_num_rows is not a valid resource. Any ideas where I am going wrong? Hello, I am having a problem.. I get this message " Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in... " whenever i am trying to work my log in script. The script is: Quote <?php $host="localhost"; $username="root"; $password="pass"; $db_name="webDB"; $table_name="webmembers"; mysql_connect($host, $username, $password) or die ('Unable to connect'); mysql_select_db($db_name) or die ('Error'); $uname= $_POST['uname']; $pword= $_POST['pword']; $urname= stripslashes($uname); $pword= stripslashes($pword); $uname= mysql_real_escape_string($uname); $pword= mysql_real_escape_string($pword); $sql= "SELECT * FROM '$table_name' WHERE username: '$uname' and password: '$pword'"; $result=mysql_query($sql); $count= mysql_num_rows($result); <----------- problem if ($count == 1) { session_register($uname); session_register($pword); header("location: loginsuccess.php"); } else { echo $result,$count; echo "Wrong Username and Password"; } mysql_close(); ?> and Quote "loginsuccess.php" <?php session_start(); if(!sesssion_is_registered($uname)) { header("location: mainpage.php"); } ?> <html> <head> </head> <body> Log in Successful </body> </html> why do i get this warning? what am i doing wrong? Is there any simpler way to create a log in page but being secure as well? Thank in advance. $sql = "SELECT current FROM LIBusersX WHERE UserKey = '$Key' AND K_Type = $type AND current > 0 "; // echo $sql . "<br>"; $query = mysql_query ($sql) or die ("E112-100A"); $total = mysql_num_rows($query) or die ("E112-101A");Hi I have a website with a few users. I set up a system so that some users (as a trial) can only log on a fixed number of times. I have a field called current that counts down to zero. However when it reaches zero I get my error E112-101A Why do I get an error? Surely I should just get $total = 0 I'm trying to loop out 10 rows of comment, but this code only displays comment one time, how do I display all rows? $query = "SELECT * FROM ".$prefix."comments WHERE userto = '".$user."' ORDER BY comment DESC LIMIT 0, 10"; $result = mysql_query($query); $num = mysql_num_rows($result); //Loop out code $i=0; while ($i < $num) { $comments=@mysql_result($result,$i,"comment"); $i++; } Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource. if ($_POST['subscribe']) { $email_subscribe = $_POST['email']; if (mysql_num_rows(mysql_query("SELECT * FROM newsletter WHERE email=$email_subscribe"))) { mysql_query("UPDATE newsletter SET active=1 WHERE email=$email_subscribe") or die ('Error updating the database'); echo "Thank you for subscribing!"; echo "<meta http-equiv=\"refresh\" content=\"0;url=javascript:history.back();\">"; } else { mysql_query("INSERT INTO newsletter (`email`,`active`) VALUES ('$email_subscribe', '1')"); echo "Thank you for subscribing!"; echo "<meta http-equiv=\"refresh\" content=\"0;url=javascript:history.back();\">"; } } elseif ($_POST['unsubscribe'] != 0) { $email_unsubscribe = $_POST['email']; if (mysql_num_rows(mysql_query("SELECT * FROM newsletter WHERE email=$email_unsubscribe"))) { mysql_query("UPDATE newsletter SET active=0 WHERE email=$email_unsubscribe") or die ('Error updating the database'); echo "You have been unsubscribed."; echo "<meta http-equiv=\"refresh\" content=\"5;url=javascript:history.back();\">"; } else { echo "Email does not exist."; echo "<meta http-equiv=\"refresh\" content=\"5;url=javascript:history.back();\">"; } I am having real problems getting mysql_num_rows function working with PHP 5 This is the split up script: index.php <?php ini_set('display_errors', 1); require_once 'config.php'; require_once 'func/func.db.php'; $connect = databaseConnect($host, $user, $password, $database); if($connect == true) { // printf("<table>"); // get it querying results for showing users entries as of now: $result = query("SELECT * FROM entries"); if($result == true) { printf("<table> <tr> <td></td> </tr>\n"); while($row = mysql_fetch_array($result)) { printf(" <tr> <td>Result row</td> </tr>\n"); } printf("</table>\n\n"); } // show form for users logged in so they can post entries, ie just one user account for now: require_once 'auth.php'; } ?> func/func.db.php <?php function databaseConnect($host, $user, $password, $database) { $connect = mysql_connect($host, $user, $password); if($connect) { $select_db = mysql_select_db($database, $connect); if($select_db) { return true; } else { return false; } } else { return false; } } function query($sql) { $sql = stripslashes($sql); $query = mysql_real_escape_string($sql); $result = mysql_query($query); if($result){ return $result; } } Then the auth.php, looks like: <?php if(isset($_POST)) { $message = 'Only registered users can post'; if(array_key_exists('submit',$_POST)) { if($_POST['username'] != '' && $_POST['password'] != '') { $username = $_POST['username']; $password = sha1($_POST['password']); // try to log user in: $result = query("SELECT * FROM users WHERE username = '$username' AND '$password'"); echo mysql_num_rows($result); } else { $message = 'You did not enter all required fields, please retry'; } } } else { $message = 'Only registered users can post'; } ?> <p><?=$message;?></p> <table> <form id="login" name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <tr> <td><label for="username">User: </label></td> <td><input type="text" id="username" name="username" value="" /></td> </tr> <tr> <td><label for="password">Password: </label></td> <td><input type="password" id="password" name="password" value="" /></td> </tr> <tr> <td><input type="submit" id="submit" name="submit" value="Login" /></td> </tr> </form> <table> You dont need to know whats in config.php since thats just full of my database connection variables, like the hostname, user, password and database, but its saying mysql_num_rows is an invalid function, since maybe its because its lost connection to the database, but how would I get around this? I thought about maybe making it connect to the database again, but is there any point in doing this? This is the actual error I get: Quote Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /www/jeremysmith.me.uk/html/blog-dev/auth.php on line 17 Any help is much appreciated, Jez. Hi All, I think im having one of those days when you want to rip your hair out... My problem is... I want to produce the total number of results in my table that match a particular query... that query in English is... calculate the total number of records where field category = C Category... When im in phpMyadmin and perform a search it finds all the records that have the value of C Category in the category field. If I then choose 'show php code' i get: $sql = "SELECT * FROM `staff` WHERE `category` = \'C Category\' LIMIT 0, 30 "; In my php document, i use... Code: [Select] <?php include ('config.php'); $sql="SELECT * FROM `staff` WHERE `category` = \'C Category\' LIMIT 0, 30 "; $result=mysql_query($sql); $num_rows = mysql_num_rows($result); echo $num_rows; ?> But I get a blank page... what am I doing wrong? Cheers I know im being blind today but can someone point out why: Code: [Select] $query = "SELECT peopleID FROM numpeople WHERE ID = '3';"; $result = mysql_query($query) or die("failed."); $row = mysql_fetch_row($result); $numpeople = mysql_num_rows($result); echo "<br /> row $row[1]"; echo "<br />numpeople $numpeople"; $numpeople returns 2, but $row[1] is undefined? $row[0] is fine. (The value of $row[0] is 7 and $row[1] should be . This is the second error that I really cant see.... ok guys, im going out the door so forgive me for not showing any code..but I have a while loop whithin a while loop to display rows for two different id's. I have a mysql_num_rows vaiable set that displays 0 because there are 0 rows with the userid of 1...then it displays 2 because there are 2 rows with the userid of 3..now what i want to do is find a way to omit the return of 0 so that i can use the return of 2 alone. sorry if im not clear enough. Im trying to figure out if a user has already downloaded something so im seeing if they have a uid (user id) in the database along with the nid (note id) that they are trying to download. I echoed out the sql and it returned this: Quote SELECT * FROM purchases WHERE uid =1 AND nid =7 i manually ran that sql in phpmyadmin and it returned a couple rows. However my var $rows = mysql_num_rows($res2) has no value when i echo is out. Appriciate any help here is my code: Code: [Select] <?php $sql2 = "SELECT * FROM purchases WHERE uid =".$user_id." AND nid =".$id; $res2 = mysql_query($sql2) or die (mysql_error()); $rows = mysql_num_rows($res2); ?> Get an error saying: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\admin\delete.php on line 16 Sorry, but we can not find an entry to match your query Surely this means the code has worked because of the last line, but i can't get rid of the error! $q = "DELETE FROM `stocklist` WHERE `Stock Number`='".$rec."'"; $res = mysql_query($q, $link) or die (mysql_error()); $anymatches = mysql_num_rows($res); if ($anymatches == 0) die ('Sorry, but we can not find an entry to match your query<br><br>'); echo '<h1>Entry has been deleted!</h1><br><br>'; mysql_close($link); I have the following code... Code: [Select] $num_rows = mysql_num_rows($rsSinglesMatch); //$num_rows now contains the number of rows from the query echo $num_rows; if ($num_rows > 0 ) { echo $ssPlayerNumber; echo ("YEX"); } else { echo "ROWS"; } $myrow = mysql_fetch_row($rsSinglesMatch); //$rsSinglesMatches = mysql_fetch_assoc($rsSinglesMatch); print_r($myrow); // if (!($rsSinglesMatches==0) || !($rsSinglesMatches_BOF==1)) if ($myrow > 0) { echo $myrow; } else { echo "Rows not counted: "; } And I can't get the mysql_num_rows and mysql_fetch_rows to work. Currently it displays Rows not counted: and ROWS if I ask it to display the number of rows it shows it as being 0. Let me know if you see anything or if I need to post anything else. I am getting the following warning with the code below.Can someone please point me why the warning ? Warning Code: [Select] Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/r.php on line 500 Code Code: [Select] $sql = "SELECT * FROM funeral WHERE name='".$name."' AND phone='".$phone."'"; $result = mysql_query($sql); if((mysql_num_rows($result)) == 0) { $insertsql = "INSERT INTO funeral (name, street, city, shrtstate, state, pincode, phone) VALUES ('".$name."', '".$street."', '".$city."', '".$shrtstate."', '".$state."', '".$pincode."', '".$phone."')"; $insert = mysql_query($insertsql); } Hi all, I have been running into a couple of errors messages that I have not been able to debug (below): 1. Undefined var Use1 2. mysql_num_rows(): supplied argument is not a valid MySQL result resource My code is as follows: Code: [Select] <?php // Script Error Reporting error_reporting(E_ALL); ini_set('display_errors', '1'); ?> <?php $results = ""; if(isset($_GET['PlantID'])) { include_once "scripts/connect_to_mysql.php"; $PlantID = $_GET['PlantID']; $sql = mysql_query("SELECT * FROM plants WHERE PlantID='$PlantID'"); $plantCount = mysql_num_rows($sql); if($plantCount > 0) { while ($row = mysql_fetch_assoc($sql)) { $PlantID = $row["PlantID"]; $BotanicalName = $row["BotanicalName"]; $CommonName = $row["CommonName"]; $HardinessZones = $row["HardinessZones"]; $Type = $row["Type"]; $Height = $row["Height"]; $Spread = $row["Spread"]; $Flower = $row["Flower"]; $BloomTime = $row["BloomTime"]; $Foliage = $row["Foliage"]; $FallColor = $row["FallColor"]; $Fruit = $row["Fruit"]; $Light = $row["Light"]; $Soil = $row["Soil"]; $Growth = $row["Growth"]; $Trimming = $row["Trimming"]; $Fertilization = $row["Fertilization"]; $OtherMaintenance = $row["OtherMaintenance"]; $Use1 = $row["Use1"]; $Use2 = $row["Use2"]; $Use3 = $row["Use3"]; $Use4 = $row["Use4"]; $Use5 = $row["Use5"]; $UseDesc1 = $row["UseDesc1"]; $UseDesc2 = $row["UseDesc2"]; $UseDesc3 = $row["UseDesc3"]; $UseDesc4 = $row["UseDesc4"]; $UseDesc5 = $row["UseDesc5"]; $Image1 = $row["Image1"]; $Image2 = $row["Image2"]; $Image3 = $row["Image3"]; $Image4 = $row["Image4"]; $Image5 = $row["Image5"]; $ImageDesc1 = $row["ImageDesc1"]; $ImageDesc2 = $row["ImageDesc2"]; $ImageDesc3 = $row["ImageDesc3"]; $ImageDesc4 = $row["ImageDesc4"]; $ImageDesc5 = $row["ImageDesc5"]; } } else { $results = "<h1>No Data to Run this Page!</h1>"; } } ?> <?php session_start(); // See if they are a logged in member by checking Session data $toplinks = ""; $booklinks = ""; if (isset($_SESSION['memberID'])) { $memberID = $_SESSION['memberID']; $username = $_SESSION['username']; $toplinks = '<a href="memberaccount.php?id=' . $memberID . '">Welcome, ' . $username . '!</a> | <a href="memberaccount.php?id=' . $memberID . '">My Account</a> | <a href="book.php">Your Plant Book</a> | <a href="logout.php">Log Out</a>'; $booklinks = '<form name="add_to_book" method="post" action="plantdetails.php"> <input name="memberID" type="hidden" value="' . $memberID . '" /> <input name="PlantID" type="hidden" value="' . $PlantID . '" /> <input name="BotanicalName" type="hidden" value="' . $BotanicalName . '" /> <input name="CommonName" type="hidden" value="' . $CommonName . '" /> <input name="Use" type="hidden" value="' . $Use1 . '" /> <input name="add_to_book_btn" type="submit" value="Add ' . $BotanicalName . ' (' . $Use1 . ') to Your Book!" /> </form>'; } else { $toplinks = '<a href="join.php">Join Now</a> | <a href="login.php">Login</a>'; $booklinks = '<h1>You must be logged in to Add Plant Pages and Create Plant Books! <img src="images/AddtoBook.gif" border="0" /></h1>'; } ?> <?php $errorMsg = ""; if(isset($_POST['memberID'])) { include_once "scripts/connect_to_mysql.php"; $memberIDtemp = $_POST['memberID']; $PlantID = $_POST['PlantID']; $BotanicalName = $_POST['BotanicalName']; $CommonName = $_POST['CommonName']; $Use = $_POST['Use']; $sqlCheck = mysql_query("SELECT * FROM book_temp WHERE PlantID='$PlantID' AND Use='$Use'"); $plantCountCheck = mysql_num_rows($sqlCheck); if($plantCountCheck > 0) { $errorMsg = "<h1>This Plant and Landscape Use is already in Your Book! Please select another Plant or Landscape Use.</h1>"; } else { mysql_query("INSERT INTO book_temp (memberID, PlantID, BotanicalName, CommonName, Use) VALUES ('$memberIDtemp', '$PlantID', '$BotanicalName', '$CommonName', '$Use')"); header("location: book.php"); exit(); } } ?> The particular errors are on the following lines: Code: [Select] <input name="Use" type="hidden" value="' . $Use1 . '" /> <input name="add_to_book_btn" type="submit" value="Add ' . $BotanicalName . ' (' . $Use1 . ') to Your Book!" /> $plantCountCheck = mysql_num_rows($sqlCheck); Any help would be superb, Thanks in advance! Bill C. When fetching results from a query I have always used the following method (the one i was taught) 1. get the query 2. if i know there might be more than one row returned, count the rows 3. use a for loop to get all the mysql_fetch_row results. Is there a more efficient way? eg, i am now writing a section that i know will either return one row or two, but never anymore, can i run a foreach on a mysql fetching function to get all the rows instead of counting first? (ie cutting out the middle man) I'm trying to check the number of results returned in a query. Currently there is one result being returned but i'm getting this error when I try to run line 38: Code: [Select] $num_rows = mysql_num_rows($ratings); Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/haas12/public_html/login/rateVideo.php on line 38 Rows Code: [Select] $ratingsQuery = "SELECT * FROM haas12_test.ratings "; $ratings = mysqli_query($conn, $ratingsQuery) or die ("Couldn't execute query."); $num_rows = mysql_num_rows($ratings); echo "$num_rows Rows\n"; MYSQL Client server version 5.0.45 Hi All! Got a little irritating problem going on when trying to allow a user to log on with their credentials. I've created the relevant tables, defined connection correctly etc but every time I enter in the correct user account details , it always displays the message I created for when the user account details are wrong. Here is the code: <?php ... ... $find_user_sql = "SELECT `ad_aid`, `ad_aus` FROM `ad_users` WHERE `ad_aus` = '" . $find_user_usr . "' AND `ad_apa` = '" . $find_user_pas . "'"; $find_user_res = mysql_query($find_user_sql); if(mysql_num_rows($find_user_res) > 1|| mysql_num_rows($find_user_res) < 1){ ?> <div id="loginbox"> <div id="loginbox-logo"> </div> <div id="loginbox-content"> <div id="content-error"> <p>The details you entered were incorrect.</p> </div> <form action="login.php" method="post"> <p>Admin Username:<br /> <input type="text" name="ad_user" autocomplete="off" /> </p> <p>Admin Password:<br /> <input type="password" name="ad_pass" autocomplete="off" /> </p> <p> <br /> <input type="submit" name="ad_submit" value="Log me in »" id="login_button" /> </p> </form> </div> <div id="loginbox-bottom"> </div> </div> <?php include_once('includes/footer.php'); $insert_fail_attempt_sql = "INSERT INTO `ad_fail_log` VALUES (NULL, NULL, '" . visitorIP() . "')"; mysql_query($insert_fail_attempt_sql); } else{ include_once('includes/header.php'); $find_user = mysql_fetch_assoc($find_user_res); session_start(); $_SESSION['ad_user'] = $find_user['ad_aus']; $_SESSION['ad_aid'] = $find_user['ad_aid']; ?> <meta http-equiv="refresh" content="3;url=../ad/index.php"> <div id="loginbox"> <div id="loginbox-logo"> </div> <div id="loginbox-content"> <p>Logging In...<br /><br /><br /><br /> <center><img src="images/login-loader.gif" /></center> </p> </div> <div id="loginbox-bottom"> </div> </div> <?php include_once('includes/footer.php'); } } }else{ include_once('includes/header.php'); ?> What the aim of the script is, is to allow users to log in then be taken to a page called index.php . I also have a include php script called check.php (below) which checks users accounts: <?php session_start(); if(!empty($_SESSION['adm_user']) && !empty($_SESSION['adm_aid'])){ $check_user_sql = "SELECT `adm_ana`, `adm_per` FROM `pb_admin_users` WHERE `adm_aus` = '" . $_SESSION['adm_user'] . "' AND `adm_aid` = '" . $_SESSION['adm_aid'] . "'"; $check_user_res = mysql_query($check_user_sql); if(mysql_num_rows($check_user_res) > 1 || mysql_num_rows($check_user_res) < 1)){ $check_user = mysql_fetch_assoc($check_user_res); $_SESSION['adm_name'] = $check_user['adm_ana']; $_SESSION['adm_perm'] = $check_user['adm_per']; }else{ header('Location: https://*website*/' . DIR_ADM . '/login.php'); die($check_user_sql); } }else{ header('Location: https://*website*/' . DIR_ADM . '/login.php'); die($check_user_sql); } ?> I know it's got something to do with the if(mysql_num_rows($find_user_res) > 1|| mysql_num_rows($find_user_res) < 1){ , but I don't know why its rejecting correct username and password . I've tried fiddling around with the mysql_num_rows value to 1 or 0 or ==1 etc but it will only do one of the following: - State that my username and password are incorrect(when they're not) OR - Seem as if it is logging in by displaying "logging in" then for it to only display the login.php page again I would be very grateful if anyone could give me some pointers!! |