mysql_fetch_assoc() dies and gives error on random page loads? - php

I've got a page that contains a fair few database queries, each appended with or die(). I'm loading this page every 1 second for testing, and on random page loads (it could take two, it could take five, or ten) die() is switched and an error given.
I broke down the script, and managed to isolate the particular offending query, which is:
$fetch = mysql_fetch_assoc($result) or die("Error 3:" . mysql_error());
This particular line is contained within:
if($size > 0) {
$off_id = array();
while($row = mysql_fetch_assoc($result)) {
$off_id[] = $row['off_id'];
}
echo '<pre>';
var_dump($off_id);
echo '</pre>';
$rand = rand(0,$size);
$off_id = $off_id[$rand];
$query = "UPDATE rotation_data SET hit_counter = hit_counter + 1 WHERE off_id = '{$off_id}'";
$result = mysql_query($query) or die("Error 1:" . mysql_error());
$query = "SELECT * FROM offer_data WHERE off_id = '{$off_id}'";
$result = mysql_query($query) or die("Error 2:" . mysql_error());
$fetch = mysql_fetch_assoc($result) or die("Error 3:" . mysql_error());
$offer_url = $fetch['url']; $geo_target = $fetch['geo_target']; $blank = $fetch['blank'];
}
Things I noticed:
No mysql_error() is returned/printed. Only Error 3: is.
The $off_id array dumps correctly each and every time, so there's always an $off_id to be used in the previous $result query, and if there wasn't, that should trigger die() for the $result query instead.
I don't really understand why this would occur on random page loads, and not all the time, as this perhaps points to it not being a syntax issue, but a load issue?
However, even if it's a load issue, I don't understand why that particular query would fail and trigger a die() while the others are fine.
Any help in understanding why this might be, and suggestions of what I could do to fix this would be greatly appreciated!

I am guessing that your query here returns no results:
$query = "SELECT * FROM offer_data WHERE off_id = '{$off_id}'";
The following statement will not return FALSE, just an empty result set into $result.
// No results here this time...
$result = mysql_query($query) or die("Error 2:" . mysql_error());
And then you attempt to fetch a row from an empty result resource. This results in FALSE not because of error, but because there are no rows to fetch, and your short-circuit evaluation calls die().
We cannot see where you are setting $size, but it's possible that you are occasionally reading past the array bounds of $off_id by reaching a random value that is larger than that array.

Related

PHP count rows of specific entries in database

New to PHP and overwhelmed by all the different solutions to similar problems. I don't know if I have a coding problem, a multiple query problem, or both/more.
In one php file I am opening a connection, running a query, and then on success counting the number of times that entry appears in the database... or at least attempting to.
// $team1, $team2 and $page come in through _POST up here...
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// build long query at this point...
$result = mysqli_query($connection, $query);
//I was successful getting it into the database, now I want to count how many times each entry appears.
if ($result) {
$team1result = mysqli_query($connection,"SELECT * FROM {$page} WHERE 'vote' = {$team1}") ;
$team1row = mysqli_fetch_row($team1result);
$team1count = $team1row[0];
$team2result = mysqli_query($connection,"SELECT * FROM {$page} WHERE 'vote' = {$team2}") ;
$team2row = mysqli_fetch_row($team2result);
$team2count = $team2row[0];
echo $team1count . " and " . $team2count;
}
I'm able to insert into the database just fine but then my console.log lights up with...
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in ...
Thanks for all the help tonight.
SOLUTION (Thanks to wishchaser):
if ($result) {
$team1rows = mysqli_num_rows(mysqli_query($connection,"SELECT * FROM $page WHERE vote = '$team1'"));
$team2rows = mysqli_num_rows(mysqli_query($connection,"SELECT * FROM $page WHERE vote = '$team2'"));
echo $team1 . " : " . $team1rows . " | ". $team2 . " : ". $team2rows;
}
There were no resulting rows for queries $team1result and $team2result. That is why you are getting this error.
use a if statement to check this
if($team1result)
$team1row = mysqli_fetch_row($team1result);
if($team2result)
$team2row = mysqli_fetch_row($team1result);
You will not get the errors.
And for counting the number of rows that a query result, use the folowing
$rows=mysqli_num_rows(mysqli_query($query));
and a good practice of finding the mistake in your query statement would be to echo it.
in this case
echo "SELECT * FROM $page WHERE vote = '$team1'";
echo "SELECT * FROM $page WHERE vote = '$team2'";
check if the echoed query has no mistakes(like an undefined variable).
You can easily count this using num_rows no need to access its index and all, simply use this
echo $team1row = mysqli_num_rows($team1result);
Reference Link

PHP, MYSQL - Query fails but no error meessage appears

Back again, thanks for all the help last time. I'm running this query:
$query = "SELECT * FROM event where evLoc = ".$loc." AND evChar = ".$char;
var_dump($query);
$result = mysql_query($query, $con) or die('Error 1:'.mysql_error());
if ($result) {
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
var_dump(mysql_num_rows($result));
exit();
I get a message Error 2: but no mysql_error printed out. The var_dump($query) printed out a query that ran without errors in phpMyAdmin. The var_dump(mysql_num_rows($result)) did not print.
This is a case of being too cautious and applying error checking where it doesn't belong.
Don't call die() in partnership with a fetch call. The fetch intentionally returns FALSE when there are no rows available, so you don't have an error, just no rows.
// No rows were returned, wich is FALSE
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
Instead, don't call die() here:
$row = mysql_fetch_array($result);
if ($row) {
// you got something
}
Or this way:
if ($row = mysql_fetch_array($result)) {
// you got something.
}
If multiple rows are expected to be returned, fetch in a while loop.
while ($row = mysql_fetch_array($result)) {
// loops until you're out of rows
// or not at all if you have no rows
}
Obviously, your request returns 0 rows and mysql_fetch_array returns FALSE
Apply Single Quotes in the fields of your query
$query = "SELECT * FROM event where evLoc = '".$loc."' AND evChar = '".$char."'";
You can write these in short form too. Like
$query = "SELECT * FROM event where evLoc = '$loc' AND evChar = '$char'";
Next, you might want to change your fetch portion.
while($row = mysql_fetch_assoc($result)) {
....
}
When you use this, you will avoid the error you would receive when no rows are returned.

Not getting appropriate php string result from mysql_query()

I'm looking to label a string based on database results. I have the following code:
$loc1 = "A";
$query = "SELECT loc FROM User where nick='".$users[$j]."'";
$loc = mysql_query($query);
if($loc == 1)
$loc1 = "A";
if($loc== 2)
$loc1 = "B";
The loc1 location is always "A". I've confirmed that the query works in MySQL and I'm having a difficult time understanding why this simple case is not working. I would appreciate your help!
The function mysql_query does not return the value of the column fetched, instead it returns a MySQL resource which you use to extract the column value returned by the query.
Change:
$loc = mysql_query($query);
to:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
$loc = $row["loc"];
}
You are storing mysql_query() return value in $loc which is a resource.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
So, $loc is not 1 or neither equals to 2.
You need to use mysql_fetch_array / mysql_fetch_object, etc to manipulate the resource.
You must fetch the recordset with, in example mysql_fetch_row
Example #1 Fetching one row with mysql_fetch_row()
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
But, be careful with SQL injection attacks!
http://es.php.net/manual/en/security.database.sql-injection.php

Basic PHP/MySQL Error with mysql_fetch_array()

The error I get:
...mysql_fetch_array() expects parameter 1 to be resource, boolean given...
awayid is in the address bar properly. I can print it out just fine, but for some reason the following code gives me the above error.
$result = mysql_query("select * from team where id=" . $_GET['awayid']);
$row = mysql_fetch_array($result);
EDIT Tried the mysql_error(). It seems I forgot to select a database... however, even why I use mysql_select_db('gamelydb'); I still get the mysql error No database selected
Your query is failing... Therefore $result is set to false.
$result = mysql_query("select * from team where id=" . $_GET['awayid']);
var_dump($result); // bool(false)
Call mysql_error() to get the error message for your query:
echo mysql_error();
Your query is failing and returning a boolean FALSE. Try this:
$result = mysql_query("select ...") or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^---- add this
This will kill the script and show you the exact reason the query is failing.
mysql_query() returns false if the query is unsuccessful, i.e. an error occured. That is why you need to check $result for being false first.
Use mysql_error() to output the error.
You need to be sure there is results from your query :
while ($row = mysql_fetch_array($result)) {
// echo $row[] ... ;
}
First of all, your query is very open to SQL injection attacks. Do not directly insert anything from $_GET or $_POST (or really anywhere) into your query. At the minimum, use mysql_real_escape_string on the variable.
mysql_query is returning false becuase there is something wrong with the query. You can use mysql_error to see what the last reported error is.
if ($result = mysql_query("select * from team where id='" . $_GET['awayid']) . "'") {
$row = mysql_fetch_array($result);
}
else {
echo mysql_error();
}
Anyway...you know that writing a $_GET parameter right into the SQL query is very very bad? Try it with PHP Data Objects.
Did you try and search around first Tory, we answer these questions over and over again, next time please search around.
The reason why this error occurs is because your running a query with mysql_query that fails, because it fails it returns false, you then pass the value of false to mysql_fetch_array, it's like doing mysql_fetch_array(false)
You need to make sure that mysql_query is successful:
try something like this:
if(false !== ($result = mysql_query("select * from team where id=" . $_GET['awayid'])))
{
$row = mysql_fetch_array($result);
}else
{
die("Query has failed: " . mysql_error())
}

mysql_num_rows error in PHP with mysql_query

Hi i am too new too php and mysql and i want to count the member number due to the search made by user. However, mysql_num_rows doesnt work.
mysql_num_rows(mysql_query("SELECT * FROM members WHERE $title LIKE '%$_POST[search]%' LIMIT $start,$member_number"));
It says "mysql_num_rows(): supplied argument is not a valid MySQL result resource in ..."
NOTE: $title is a select menu which user choose where to search. LIMIT is, as you know :), number of member which is shown in a page.
And also $start= ($page-1)*$member_number; in order to set the first entry in that page. I think the problem is here but i cant solve it. :(
Your query probably has an error, in which case mysql_query will return false.
For this reason, you should not group commands like this. Do it like this:
$result = mysql_query("...");
if (!$result)
{ echo mysql_error(); die(); } // or some other error handling method
// like, a generic error message on a public site
$count = mysql_num_rows($result);
Also, you have a number of SQL injection vulnerabilities in your code. You need to sanitize the incoming $search variable:
$search = mysql_real_escape_string($_POST["search"]);
... mysql_query(".... WHERE $title LIKE '%$search%'");
if $start and $end come from outside, you also need to sanitize those before using them in your LIMIT clause. You can't use mysql_real_escape_string() here, because they are numeric values. Use intval() to make sure they contain only numbers.
Using a dynamic column name is also difficult from a sanitation point of view: You won't be able to apply mysql_real_escape_string() here, either. You should ideally compare against a list of allowed column names to prevent injection.
you have to use GET method in your form, not POST.
mysql_num_rows doesn't make sense here.
If you're using limit, you already know the number*.
If you want to know number, you shouldn't use limit nor request rows but select number itself.
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members WHERE $title LIKE '%$search%'";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$members_found = $row[0]
in case you need just 5 records to show on the page, no need for mysql_num_rows() again:
// Get LIMIT params
$member_number = 5;
$start = 0;
if (isset($_GET['page'])){
$start = abs($_GET['page']-1)*$member_number;
}
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members
WHERE `$title` LIKE '%$search%'
LIMIT $start, $member_number";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
while($row = mysql_fetch_assoc($res){
$data[] = $row;
}
Now you have selected rows in $data for the further use.
This kind of error generally indicates there is an error in your SQL query -- so it has not been successful, and mysql_query() doesn't return a valid resource ; which, so, cannot be used as a parameter to mysql_num_rows().
You should echo your SQL query, in order to check if it's build OK.
And/or, if mysql_query() returns false, you could use mysql_error() to get the error message : it'll help you debug your query ;-)
Typically, your code would look a bit like this :
$query = "select ..."; // note : don't forget about escaping your data
$result = mysql_query($query);
if (!$result) {
trigger_error(mysql_error()." in ".$query);
} else {
// use the resultset
}

Categories