This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php warning mysql_fetch_assoc
i am just implementing a simple part of my website that just takes a variable from the header(subid) checks it with the database and then outputs the other fields related to the variable.
However i am getting this error -
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/report.php on line 14
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''/home/admin/public_html/log/log_274b43e6ad_New Text Document (7).txt.txt' at line 1
Here is the code for my page that does it all
include 'connect_to_mysql.php';
$sql_header = mysql_query("SELECT * FROM system");
$header_array = mysql_fetch_assoc($sql_header);
$total_scans = $header_array['total_scans'];
$malware_detected = $header_array['malware_detected'];
$total_users = $header_array['total_users'];
$report_id = $_GET['log'];
var_dump($report_id);
$sql_report = mysql_query("SELECT * FROM logs WHERE log_name='$report_id");
var_dump($sql_report);
$report_array = mysql_fetch_assoc($sql_report) or die(mysql_error());
$file_name = $report_array['file_name'];
$file_size = $report_array['file_size'];
$submission_date = $report_array['submission_date'];
$result = $report_array['result'];
$status = $report_array['status'];
Any ideas on what could be wrong? I have tried everything and checked my database, all the names are correct and everything, i even checked the $report_id variable in the database and it matches, so i am not sure why it is getting an error.
Thanks for the help
Your code it not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what is going wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$sql_report = mysql_query("SELECT * FROM logs WHERE log_name='$report_id");
// Bail out on error
if (!$sql_report)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In your specific case, you are missing a closing ' in
WHERE log_name='$report_id")
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$report_id = mysql_real_escape_string($_GET['log']);
for this to work, you need to put every value in your query into quotes.
You forgot a quote '$report_id' .
Here there are two things you have to notice :
1) the warning with mysql_fetch_assoc() .
This warning will occur when the argument passed to it is not an vaide mysql resource ,ie,
the mysql_connect() returned null object(failed to return conection object) . This inturn is caused due to fact that arguments passed to mysql_connect() are bad database credentials.
this case is usualy traped by using
is_resource($con)
call which returns true if $con is an valid resource.
2) The error as described in the error discription is due to bad syntax of query.
"SELECT * FROM logs WHERE log_name='$report_id"
here you ommited closing brace for $report_id
"SELECT * FROM logs WHERE log_name='$report_id'"
3) data base access :
An generel method of accesing database is by using an class , that access the database credentials through Accessor methods like setUname() , SetPasswd() etc , where the method itself will trim , escape and sanitize the credentials before it is passed to database.
this will prevent sql injection attack
Related
I want to get some data from a Sphinx server and pass it to MySQL to execute some queries. I'm new to PHP so probably I'm missing something here. I've looked for similar questions but can't find anything so maybe you can help me.
The error is in the first while. I'm pretty sure it's due to the $rown variable but don't know the reason. (I've verified that I can retrieve data from the connections so it is passing the data where the error lies - could be the sql syntax of the query but that seems fine).
Edited the code thanks to the comments below, now I get the error: Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\test3.php on line 20. This is because the query failed, I still suspect it is because $rown.
$sphinxcon = mysqli_connect...
$mysqlcon = mysqli_connect...
$query = "SELECT names FROM iproducts LIMIT 0,1000";
$raw_results= mysqli_query($sphinxcon, $query);
//Until here works ok, now I want to pass $raw_results to MySQL
while ($row = mysqli_fetch_object($raw_results)) {
$rown = $row->names;
$mquery = "SELECT text FROM claims WHERE EXISTS ($rown) LIMIT 0,1000";
$mysqlresults = mysqli_query($mysqlcon, $mquery);
while ($final = mysqli_fetch_object($mysqlresults)) //this is line 20
{
printf ("%s<br />", $final->text);
}
}
Thanks :)
Well $row contains an object, so would have to use it as such, maybe
$rown = (string)$row->names;
... assuming you want the variable to contain the 'names' attribute you just SELECTed from Sphinx index.
As for the mysql EXISTS(), no idea what you really doing here, seems confused. How you structured it currently suggests that 'names' attribute in sphinx contains a complete SELECT query, that mysql could execute for the exists condition. That seems unlikely.
Guessing you meaning to more normal query something like
$mquery = "SELECT text FROM claims WHERE text LIKE '%$rown%' LIMIT 0,1000";
But that is subject to SQL injection, particully if names might contain single quotes. SO should escape it. Perhaps
$rown = mysqli_real_escape_string($mysqlcon, $row->names);
But might be worth reading up on prepared queries.
btw, the 'Error' you getting, is because you creating an invalid query and not dealing with it. So $mysqlresults is FALSE.
$mysqlresults = mysqli_query($mysqlcon, $mquery) or die("Mysql Error: ".mysqli_error($link)."\n");
I am currently working on a project for a client but because I am new to pdo I have no clue how to hand the error it keeps spitting out. The code I am working with is not mine either, so that adds a bit of confusion to the mix. It keeps telling me:
Query failed: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near '' at line 1
I have narrowed down the error to these lines:
$regid = $dbh->lastInsertId('');
$dupsid = true;
while ($dupsid){
srand((double)microtime()*1000000);
$maxrand = 100000000;
$rand_sid = rand();
$check_sid = "select reguniqid from v_events_registrants where reguniqid = :RAND_SID";
$stmt = $dbh->prepare($check_sid);
$stmt->bindValue(':RAND_SID', $rand_sid);
$stmt->execute();
$num_result = $stmt->rowCount();
if ($num_result == 0) $dupsid = false;
}
$uniqid_upd = "update v_events_registrants set reguniqid = :RAND_SID where registrant_id = :REGID";
$stmt = $dbh->prepare($uniqid_upd);
$stmt->bindValue(':RAND_SID', $rand_sid);
$stmt->bindValue(':REGID', $regid);
$stmt->execute();
in this case here $reg is the primary key of the table in which the last few items were added. Initially I thought that was the issue but when I cleared it of ', and " I get an invalid id error, which I am guessing is from the next execution of the pdo. Please help as this error is really starting to hold me back from completing this project for my client.
Your first line defines $reg, then you try to use the undefined $regid
Nearly positive $regid is not defined, at least not within the scope of the code you included.
Trace that variable back or define at as something and you should be fixed.
Most likely your error lies somewhere else.
So, first of all get rid ov any try..catch blocks in your code
Then turn error reporting on
Then run your code again and find the real place where error occurs from the stack trace.
Then you get to erroneous query, write it this way
select
reguniqid
from
v_events_registrants
where
reguniqid
=
:RAND_SID
and watch the line number - it will help you locate the problem spot.
As your $rand_sid is of type integer, both times you use bindValue for $rand_sid you should add the datatype PDO::PARAM_INT (it takes PDO::PARAM_STR as default), like this:
$stmt->bindValue(':RAND_SID', $rand_sid, PDO::PARAM_INT);
I am getting an error when querying a table in my MySQL database. It's the standard one with mysqli_num_rows when there is no value in the variable that's being passed:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in folder/file.php on line 29
Problem is I can't find the syntax error. I've looked at it a ton of times. Here's what my code is:
$sql_messages = "SELECT * FROM messages WHERE to='$userid'";
$result_messages = $mysqli->query($sql_messages);
$num_rows_messages = mysqli_num_rows($result_messages);
I tried a fetch array but that gave me the similar error. Nothing is getting passed into $result_messages I suppose. I echo'ed out $userid and that has a value and I've checked my database and there is a table 'messages' with a field 'to'. I'm connected to the right database because I have this code before this query:
$sql="SELECT * FROM users WHERE firstname='$firstname' && lastname='$lastname'";
$result = $mysqli->query($sql);
$row = mysqli_fetch_array($result);
And that works fine. It is the third query on the page, is there some sort of limit? Does anyone see a syntax error that I'm overlooking? Thanks, sorry if it's a small little error!
It's because $mysqli->query() returned boolean FALSE, which, according to the mysqli::query() docs, it does when an error happens. You can get more detail on the error by accessing $mysqli->errno and $mysqli->error.
I'm guessing that the root of the problem lies in the query which references a column called to, which is a MySQL reserved word. Try surrounding the word to in your query with backticks. Like this:
$sql_messages = "SELECT * FROM messages WHERE `to`='$userid'";
Really, though you should avoid naming columns and tables reserved words. Consider renaming the column if feasible.
This question already has answers here:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result [duplicate]
(6 answers)
Closed 9 years ago.
Creating a login system for something and am getting:
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in .../func/user.func.php on line 21
Here is my code:
function user_register($email, $name, $password) {
}
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT('user_id') FROM 'users' WHERE 'email' ='$email'");
//this is line 21:
return (mysql_result($query, 0) == 1) ? true : false;
}
Your SQL is full of syntax errors, single quotes are used to quote string literals, backticks (or double quotes in standard SQL) are used for identifiers. Try this:
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
You don't need to quote any of those identifiers so don't bother.
From the fine manual:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
You probably want to add some error checking after you've fixed your SQL syntax errors.
There is an error in your query. If you want to figure out what the error is, output it with mysql_error()
Your query has syntax errors. You're using single quotes on field and table names. That changes from them being field/table names to being ordinary strings. So your query boils down to count(some string) from someotherstring where yetanotherstring.
If your query call had been constructed something like this:
$result = mysql_query(...) or die(mysql_error());
you'd have been informed of the syntax error. As it stands now, your code assumes the query succeeds, which is a very bad thing to do. There's precisely ONE way for a query to succeed, and far too many ways for it to fail.
Your code has no error handling, so if anything goes wrong, it continues on blissfully unaware trying to make soup out of stones. Take a look at the examples in the manual, they all check for errors in the query before they try to analyze the result.
We have a function used within our PHP/MySQL application which returns basic configuration information, it contains a simple select query and looks like this:
public function getConfigurationValue($field)
{
$res = mysql_query("SELECT `cfg_value` FROM `ls_config` WHERE `cfg_name` = '".mysql_real_escape_string($field)."'");
$cfg = htmlspecialchars(mysql_result($res,0));
return $cfg;
}
This problem we are having is that occasionally, seemingly at random, this query throws a mysql error on mysql_result saying that "supplied argument is not a valid mysql result resource". In our debugging we have determined though that this is not because $field is not being passed. Essentially, for a reason we cannot determine a perfectly valid query fails and returns no results causing an empty result set and the subsequent error. If the error was due to the mysql connection failing the script would have died well before this. Also, this function may be called 50-100 times on some page loads but it only tends to fail once on each load.
Please let me know if you need any other information to work this out.
Thanks.
searching for php "supplied argument is not a valid mysql result resource" reveals that to get the actual error, you'd need to call mysql_error, and the error that you get is because the result of the query is FALSE - this value not being a valid mysql result resource.
i.e. in short you have something like:
$res = FALSE; # should contain the mysql result but does not, due to error.
$cfg = htmlspecialchars(mysql_result($res,0)); # the attempt to call mysql_result on invalid argument errors out.
So you'd want to use something like this:
$query = "SELECT * FROM cats WHERE id=$id";
$qr1 = mysql_query ($query)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
You might want to give this a shot and see what the underlying error message says.
Given that the error is "MySQL server has gone away", There can be multitude of reasons for it - this article would be a good start to investigate. Searching suggests also some php-related and stack-specific bugs, so it looks like you might need to debug it with a closer attention.
Maybe try to duplicate the setup on another box and then start experimenting with the versions/settings, and see if any of the already reported scenarios match your case. Unfortunately, seems there's no single simple answer to this.