mysql_result() error happening all of a sudden - php

I recently rebuilt my website and now I'm getting this error:
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /home/xx/public_html/asdf.com/comsel.php on line 28
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /home/xx/public_html/asdf.com/comsel.php on line 29
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /home/xx/public_html/asdf.com/comsel.php on line 30
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /home/xx/public_html/asdf.com/comsel.php on line 31
Those lines are as follows:
mysql_connect($dbhost,$dbuser,$dbpass)
or die("Error: Failed to connect to database");
mysql_select_db($dbname)
or die("Error: Failed to select databse");
$query = "SELECT * FROM foxlose ORDER BY RAND ( ) LIMIT 1";
$result = mysql_query($query);
$title = mysql_result($result,$i,"title");
$link = mysql_result($result,$i,"link");
$nomen = mysql_result($result,$i,"name");
$text = mysql_result($result,$i,"text");
mysql_close();
The last four lines before mysql_close(); are lines 28-31.
Only here's the thing: those lines were the same in the old version of my site, and they worked. I can't figure out what's changed. The code also works fine when I use my computer as a server and host it locally.
Any idea what this error is trying to tell me?
Edit: Added all mysql in the document.

It seems to me odd that you close the connection to a database by:
mysql_close();
and then you use
$variable = mysql_result(...);
Generally, if you want to know the reason of the error use the function mysql_error.

Try removing the space after RAND:
$query = "SELECT * FROM foxlose ORDER BY RAND() LIMIT 1;

There are several things you could do here.
Check the mysql_query connection is actually set. Alternately youcan ensure the connection is being passed by passing it to the mysql query
i.e.
mysql_query($query, $connction);
Additionally, Thomas Clayson pointed out, ensure you are getting results. If there are no results mysql_result will throw an error
Ensure mysql_select_db (assuming you are using this), is connecting to the database properly.
Depending on versions and such you may need a semicolon to close your mysql statement
i.e.
$query = "SELECT * FROM foxlose ORDER BY RAND () LIMIT 1;";
Much of this has been taken from other people with similar issues. full credit (and more ideas) here: http://www.daniweb.com/forums/thread26425.html

Related

Creating a function to retrieve information from SQL

I've searched the site for an answer but couldn't find any answer for my specific problem that worked.
I have two files, the first one is my index.php of-course, the second is my functions.php file, which obviously contains the functions, I made this function:
function sql_get($lang, $tabler, $rower){
if ($lang == "heb") {
$result = mysql_query("SELECT * FROM %s WHERE id = 0",
mysql_real_escape_string($tabler));
$row = mysql_fetch_array($result);
return $row['$rower'];
}
else if ($lang == "rus") {
$result = mysql_query("SELECT * FROM %s WHERE id = 0",
mysql_real_escape_string($tabler));
$row = mysql_fetch_array($result);
return $row['$rower'];
}
this code supposed to get an information about the language (from a get, it gets it, it's all fine with that), the sql table and the specific row from this table where the id is 0.
and return the information from the row inserted.
My warnings and errors when the language is "heb":
Warning: mysql_query() expects parameter 2 to be resource, string given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 16
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 17
and when the language is "rus":
Warning: mysql_query() expects parameter 2 to be resource, string given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 23
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/elenbyin/public_html/elenby.co.il/vadim/functions.php on line 24
the function call in the index.php file looks like that:
I will be thankful for the people who will try to help and especially for those who will help me.
Thanks A lot!
Firstly, you haven't connected to the database inside your function. If you've opened your database somewhere then you can get away with this with mysql, but you shouldn't.
Secondly, you're passing your variable as a second parameter to mysql_query(), but mysql_query() expects the query to be complete as the first parameter, and the second parameter should be the connection resource tht connects to the database, which you haven't got.
From the structure of the query it looks like you intend to use sprintf() to create it.
This should create the query for you, assuming you have opend a databse connection:
$query = sprintf("SELECT * FROM %s WHERE id = 0",
mysql_real_escape_string($tabler));
$result = mysql_query($query) or die(mysql_error());
Note: mysql is deprecated. You shouldn't use it. Use mysqli or PDO instead. You'll need to be more rigorous about passing in your database connecions if you use mysqli.
As Amal suggested - better not use mysql_* functions cause not only they're deprecated but also vulnerable to sql-injection.
That said, in order to fix your code you should do:
$table = mysql_real_escape_string($tabler);
$sql = "SELECT * FROM $table WHERE id = 0";
$link=mysql_connect('host','user','pass');
$result = mysql_query($sql, $link);
...
as the second (and optional) parameter of mysql_query should be a resource - not a string!

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. :-)

PHP printing mysql data via json_encode() [duplicate]

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;

What's the best way to access a MS Access database using PHP?

I need to access some data from an MS Access database and retrieve some data from it using PHP.
I've looked around the web, and found the following line which seems to correctly connect to the database:
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=C:\wamp\www\data\MYDB.mdb");
However, I have tried to retrieve some data in the following way:
$query = "SELECT pageid FROM pages_table";
$result = mysqli_query($conn, $query);
$amount_of_pages = 0;
if(mysqli_num_rows($result) <= 0)
echo "No results found.";
else
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
$amount_of_pages++;
And was presented with the following errors:
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\wamp\www\data\index.php on line 19
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\data\index.php on line 23
No results found.
I don't really understand the connection to the Access database, is there something I should be doing differently?
Thanks in advance for any help.
I don't think you can use MySQLi with anything other than a MySQL db. You'll probably need to use an ODBC connection.
The mysqli_* functions are for MySQL databases only, and can't be used for Microsoft Access databases. See PHP's ODBC documentation for details on how to use these.

Categories