PHP printing mysql data via json_encode() [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
I have tow mysql data bases. the first data base location is latin1_swedish_ci and the second data base is utf_unicode_ci.I am trying to read tha data bases with tha php code below.
<?php
mysql_connect("localhost","admin","***");
mysql_select_db("MyDB");
$sql=mysql_query("select * from menu where avail=1");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
When I am runing this code via my php server the first data base the one with latin1_swedish_ci is readed but when I am trying to read the second one it displays the following messages:
"Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in...."
"Notice: Undefined variable: output in...."
I tried to give
mysql_query("SET NAMES utf8;");
in my code but it didnt worked
Can anyone tell me what is going wrong here?

First of all, you should add $output = array(); before the loop.
Then, fix your query so it doesn't fail. If mysql_query() returns a boolean (false), it means the query failed.
You can add an ugly construct to see why it failed:
$sql=mysql_query("select * from menu where avail=1") or die(mysql_error());

You had an error in your query. The error caused this line:
$sql=mysql_query("select * from menu where avail=1");
to return false. This false when fed to the next line:
while($row=mysql_fetch_assoc($sql))
raised the first error. The while was skipped hence this line was never executed:
$output[]=$row;
Hence the second warning.
Add a mysql_error() after your mysql_* statements like this and make this a habit:
mysql_connect("localhost","admin","***") or die(mysql_error());
.
.
.
mysql_select_db("MyDB") or die(mysql_error());
.
.
.
$sql=mysql_query("select * from menu where avail=1") or die(mysql_error());
These the die(mysql_error()) statement terminates the script after displaying the error message. While it may or may not be necessary to make the script die on mysql errors, most people keep it that way. Instead of using die statement, you can check the return value instead and terminate the script if necessary.
The error in your case seems to be at the database selection line. May be the database name you specify in mysql_select_db was incorrect or may be you do not have permission to read that database (establishing connection with a given user name/password does not mean that that user can read all databases). Post the error message (again).

Try mysql_fetch_array instead of mysql_fetch_assoc
Also define $output before you use it:
$output = array();
while($row=mysql_fetch_array($sql))
$output[]=$row;

Related

mysqli_num_rows() expects paramter though an earlier query on the same page works

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.

Error with mysql_fetch_assoc [duplicate]

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

No results from MySQL query in PHP, but 1 result via phpMyAdmin [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
mysql_num_rows(): supplied argument is not a valid MySQL result resource
Here's the deal. I wanna make a Login form, but I keep recieving the Error Message:
mysql_num_rows(): supplied argument is not a valid MySQL result resource in Line 14
My code looks like this:
if($_POST){
ob_start();
$fusuario = $_POST['fusuario'];
$fsenha = md5($_POST['fsenha']);
$sql = "SELECT * FROM usuario WHERE login='$fusuario' and senha='$fsenha'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==1)
{
session_start();
$_SESSION['admin_user'] = $fusuario;
$_SESSION['admin_id'] = $row['id_usuario'];
header("location:index.php");
}
else { $erro = 1; }
ob_end_flush();
}
?>
When I execute the SELECT query from phpMyAdmin, it returns 1 row, like it should.
When I do it via PHP, no row is returned.
Any ideas?
It appears that your mysql_query() is running into an error. Check what the error message that mysql is returning:
$result=mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result);
I'm guessing that there is a problem with your mysql connection... try explicity including the mysql connection identifier:
mysql_query($sql,[INCLUDE LINK IDENTIFIER HERE])
If you're not sure what this means, read this: http://php.net/manual/en/function.mysql-query.php
If mysql_num_rows() says that $result is not a valid resource, it's probably because the query failed, and returned FALSE instead of a resource.
You should always check for errors after running an SQL query.
See code examples that check if (!$result) ... at http://php.net/mysql_query
I see from your comment that you had no open connection to the database at the time you issued your query. That'll be a problem too. :-)

Linking PHP with mySQL problem [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home2/wizardso/public_html/tab1_content.php on line 6
this is the error that i am getting when i uploaded my db-driven webpage to my web-hosting. The same webpage was running smoothly on my localhost/ server. But its not working over the internet. Please HELP.
UPDATE
These are the contents of my file tab1_content.php
<?php
$query="select * from subcatagory where catagory_id='c001'";
$res=mysql_query($query,$con);
$query_cat="select * from catagory where catagory_id='c001'";
$res_cat=mysql_query($query_cat,$con);
$current_cat=mysql_fetch_assoc($res_cat);
?>
That error most likely results from the fact that there is something wrong with the mysql_query ("result resource") that you are calling mysql_fetch_assoc() on. Try running just the query and see what errors are returned.
All the error you posted tells you is that something went wrong with the query, it could be anything from a MySQL database connection problem to a typo in your script. Please show us your code so we can see what exactly is causing the error.
echo mysql_error();
Edit
Your code appears to look OK- are you sure that there is table within your database called "catagory" (then again- are you sure it's not "category"?), and that within that database is a record with a catagory_id of "c001"?
To test this, try echoing mysql_affected_rows(); , this gives the number of rows "affected" by the last query. If you get 0, then that means that there is no such record.
Whatever result set you're passing to mysql_fetch_assoc() is invalid because the query with mysql_query() did not complete. Check the mysql error with mysql_error()
Check your Database connectivity settings i hope that it may be one of the reason for the empty result set.
Thanks

A weird mysql_fetch_(assoc,array,object) error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php warning mysql_fetch_assoc
I have a weird problem about my script. It returns always error for mysql_fetch_array or mysql_fetch_assoc. I have used mysql_fetch many times in my project and I checked for this error many times but I am blind about what is happening. Is there something wrong about my script?
My functions aim is learning the biggest value of specified mysql field.
Here is the function:
function nextIncrement($table,$field) {
$sql = mysql_query("SELECT '$field' FROM '$table' ORDER BY '$field' DESC LIMIT 0,1");
while($row = mysql_fetch_assoc($sql)) {
$next = $row[$field];
}
$next = (int)$next;
return $next;
}
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource ...
Most likely, your mysql_query() returned false for some reason.
See the manual for a list of possible values that mysql_query() can return.
Do a echo mysql_error(); to see what's wrong.
Check to see that the query actually succeeds before proceeding to fetch results.
There may be an error in your SQL statement, or maybe you don't have an open database connection?

Categories