php/sql error - mysql_fetch_assoc() - php

I'm receiving the following error:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource..
and I can't figure out what is going on. Here is my code. I did create a database with a table named notes. Also, the database connection is working correctly. Any idea on what is going on?
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
mysql_fetch_assoc($query)
Thanks

var_dump($query);
echo mysql_error();

Did mysql_query fail and return FALSE? As the documentation explains:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
FALSE would not be a valid resource.

On the PHP page, it gives you a perfect example of how to use it and do error checking...
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
How about you go and implement the entire way making sure rows are returned, and its a valid resource, and if result is truthy?
You should always debug and never assume something executed rightfully.
In the future please read through the entire page of the function on php.net, in this case it's http://php.net/manual/en/function.mysql-fetch-assoc.php

Related

why does mysql_fetch_array() storing an empty result?

I am successfully selecting the data from database table, when ever I am trying to fetch that data in to an array with the help of mysql_fetch_array() it's not storing anything into the array.
#session.start();
$name=$_SESSION['umailid'];
$chkname1 = "select * from ".USREG." where email='.$name.'";
echo $chkname1;
// it is printing like this:
// " select * from users_temp where email='.subbu66g#gmail.com.' "
// which means query was successful, above email is there in database table
$res1 = mysql_query($chkname1, $con) or die(mysql_error());
$chkresult1 = mysql_fetch_array($res1);
echo $chresult1['name']; //its not printing anything
if ($chkresult1) //it is storing null and entering into else block
{
echo "query successful";
}
else {
echo "query was not successful";
}
And the result is "query was not successful". I think everything is fine with my select query. Then why this mysql_fetch_array() is not fetching the data?
In $chkname change to email = $name
(remove dot) or email = '$name'
And you are using mysql ,rather use mysqli or pdo sql

How to print the value of a single cell using MySQL and PHP?

This returns a blank page:
<?php
$con=mysqli_connect("xxx.x.xx.x","user","password","db");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT column FROM table WHERE id=1");
print $result;
mysqli_close($con);
?>
And this returns data:
<?php
$con=mysqli_connect("xxx.x.xx.x","user","password","db");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table");
while($row = mysqli_fetch_array($result))
{
echo $row['column_1'] . " " . $row['column_2'];
echo "<br>";
}
mysqli_close($con);
?>
What is wrong with the first block of code that prevents it returning any data?
http://php.net/manual/en/mysqli.query.php
tells me that mysqli_query returns a mysqli_query object. Not a primitive value like string or int.
The exact line that says this is:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Hence the first block does not work because the first block assumes the value in the column is automatically returned.
In fact, if you used the same SELECT column from table where id=1, you still have to use the while loop to extract the values because it is STILL a mysqli_result object you are getting back.
By while loop I mean this:
while($row = mysqli_fetch_array($result))
{
echo $row['column_1'];
echo "<br>";
}
I hope this answers your question.

Empty MySQL query result not working as expected?

I am using the following script to check a code, so when the user enters the survey code they get the survey that is associated with that code. The part that fetches the survey is working as its supposed to, but I cant seem to get the error message to come up for some reason. If I enter a wrong code or no code all on the form this posts from, all I get is a blank page.
<?php
$con = mysql_connect("myhost","myuser","mypassword;
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Select mysql db
mysql_select_db("mydb", $con);
$questionaireID = $_POST['questionaireID'];
$result = mysql_query("SELECT * FROM itsnb_questionaire WHERE questionaireID='$questionaireID'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
if (empty($row['questionaireID'])) {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
} else {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
}
}
?>
It will never get there, because if the resultset is empty, it'll skip the while loop.
Try this, instead, limiting to 1 record (which is what you expect) and using an if...else instead of your while (while is only required when multiple results are expected):
$sql = "SELECT *
FROM itsnb_questionaire
WHERE questionaireID = '{$questionaireID}'
LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if ($row = mysql_fetch_array($result)) {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
} else {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
}
If number of returned rows is zero than you haven't found your result therefore you can display apropriate error message
try
if (mysql_num_rows($result)<1){
//error
}

How to check if a MySQL query using the legacy API was successful?

How do I check if a MySQL query is successful other than using die()
I'm trying to achieve...
mysql_query($query);
if(success){
//move file
}
else if(fail){
//display error
}
This is the first example in the manual page for mysql_query:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If you wish to use something other than die, then I'd suggest trigger_error.
You can use mysql_errno() for this too.
$result = mysql_query($query);
if(mysql_errno()){
echo "MySQL error ".mysql_errno().": "
.mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}
If your query failed, you'll receive a FALSE return value. Otherwise you'll receive a resource/TRUE.
$result = mysql_query($query);
if(!$result){
/* check for error, die, etc */
}
Basically as long as it's not false, you're fine. Afterwards, you can continue your code.
if(!$result)
This part of the code actually runs your query.
mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
put only :
or die(mysqli_error());
after your query
and it will retern the error as echo
example
// "Your Query" means you can put "Select/Update/Delete/Set" queries here
$qfetch = mysqli_fetch_assoc(mysqli_query("your query")) or die(mysqli_error());
if (mysqli_errno()) {
echo 'error' . mysqli_error();
die();
}
if using MySQLi bind_param try to put this line above the query
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

mysql_fetch_array problem

i am trying to do a guestbook in php but i am having some problems with mysql_fetch_array function. I don't understand why. I try to debug by putting
die("Error ".mysql_error()) but nothing prints out. I guarantee that all my variables are correctly initialized.
Here is my code :
<?php
$nbmessagesPP = 10;
mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.......
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$first_msg = ($page - 1) * $nb_of_Page;
$query = 'Select * from livredor ORDER BY id DESC LIMIT '.$first_msg.', '.$nbmessagesPP;
$rep = mysql_query($query) or exit("Error in query".mysql_error());
$v = true;
while($v){
$v = ($data = mysql_fetch_array($rep) or die ("Error fetching the data : ".mysql_error()));
echo "<p>id -> ".$data['id']."</p>";
echo "<p>pseudo ->".$data['pseudo']."</p>";
echo "<p>messages ->".$data['message']."</p>";
echo "<hr/>";
}
mysql_close();
?>
Can someone help me ;)
Your code doesn't deal with errors or the last row correctly. When $v is false, it still goes on to print some data. It would be better rewritten as:
while (($data = mysql_fetch_array($rep))) {
echo
...
}
That forces the evaluation of the fetch before moving on to the printing.
The problem is that you're trying to access elements of the result that don't exist. mysql_fetch_array returns a regular array, with integer indices. What you want is mysql_fetch_assoc, which returns an associative array.
Edit: You also have the problem Chris describes, not dealing with the last row correctly.
Generally, if you're receiving an error saying "supplied argument is not a valid MySQL result resource" it means that your MySQL query has failed, therefor not returning a valid result resource.
Try to echo out $query before sending it through mysql_query(), then try placing the echo'd query into phpMyAdmin and see if it returns any results.
Ok i have found the problem.
The problem was that in another page i had a mysql_connection and in that page i was creating a new one.
I just catch the return value of mysql_connect function and then close it with mysql_close function at the end. Like this :
<?php
$link = mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.....
while($data = mysql_fetch_array($rep)) {//i do something here}
mysql_close($link);
?>
Thanks for your answers folks :)

Categories