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.
Related
I've used PDO in my PHP application. But I have problem with fetch() function. Whenever I count the result of fetch(), it tells me there is something in resultset. But when I want to show them, it has nothing to show.
try
{
$sql = "SELECT id,salt FROM tbl_admin WHERE username = ? AND password = ? LIMIT 1";
$q = $db->prepare($sql);
$q->execute(array($username,$password));
$rows = $q->columnCount();
if ($rows > 0)
{
$r = $q->fetch(PDO::FETCH_BOTH);
echo(count($r).'<br />'); // Prints 1
print_r($r); // Nothing to print ...
die();
}
else
{
die('error');
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
May you help me please?
You're counting the number of columns, not the number of rows.
$rows = $q->columnCount();
This should be
$rows = $q->rowCount();
That said, rowCount is for UPDATE, INSERT, or DELETE queries. So that isn't the problem here.
Firstly should also be checking if $q->execute returns true or false.
Secondly you should be checking if $q->fetch returns true or false.
Given your code
$r = $q->fetch(PDO::FETCH_BOTH);
echo(count($r).'<br />'); // Prints 1
Try the following.
echo(count(false));
You'll notice that this also outputs 1.
So the solution is, that you need to check the return value of $q->fetch before assuming it returned a valid row.
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
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.
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
}
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
//$values = array();
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
}
Not able to get the userlevel field.... nor anything....
Not sure exactly what your question is, but one problem is that you're returning from within this while loop:
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
In fact, you're returning twice from within the loop... so the procLogin() function will always return a value of "gg", unless something goes wrong with your SQL query.
In general, you should avoid return statements within any loop, as it creates confusion and can lead to unexpected results.
return(array($row['member_id']));
Looks wrong - it should be:
return($row['member_id']);
You shouldn't need to define the array in the return like that.
You also use mysql_fetch_array () which returns as a numerical index - the function you probably want is mysql_fetch_assoc which is much nicer to work with as it returns the values with the keys as the column name rather than a numerical index.
Here's it again with a few tidy ups:
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['member_id'] > 0)
{
return ($row['member_id']);
}
else
{
return false;
}
}
I'm thinking, based on your comments about the userlevel, that you want to return the entire array rather than just the member_id ? Here's a slight edit to Meep3D's answer above:
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_assoc($result);
return $row;
}
else
{
return false;
}
}
This should return an array of all your table columns, if you are looking for the userlevel, presumably you should be able to access it something like:
$loginInfo = procLogin("theband","password1");
//if ($loginInfo) or something similar here
$level = $loginInfo['userlevel'];
So are you getting anything returned? That is to say, is it actually going into the while loop?
I'd use a mysql_error() function call straight after the mysql_query call to see if anything went wrong there.
Maybe there was no connection made, for example.
Are you still having issues? If so try something like:
echo $query;
after you define the query, then copy+paste that into phpmyadmin to check if there are any valid returns from the database.
After that try placing:
if (mysql_error())
{
trigger_error ("MySQL Error: ". mysql_error(), E_USER_ERROR);
}
Just after you call mysql_query. This should trigger an error if there is one giving you details of what went wrong.