I'm trying to set a simple cron script to do some database updating, and I'm pretty worthless with MySQL without ActiveRecord (I use CodeIgniter). I keep getting the error message,
mysql_fetch_object(): supplied argument is not a valid MySQL result resource
with the following code:
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$query = "select visit_e_id, visit_e_type from visits";
$result = mysql_query($query)
or die("Query failed: ".mysql_error()." Actual query: ".$query);
while($row=mysql_fetch_object($result))
{
....
}
Like I said, I'm not that great with straight PHP and MySQL (would appreciate any advice on how to include some sort of framework or ActiveRecords that could be used as part of a cron job). Any thoughts?
What happens if you assign mysql_connect as a variable and pass it in as a link identifier as a second parameter to the mysql_select_db and query functions?
$db = mysql_connect("localhost", "user", "pass") or die(mysql_error());
// Check to see if valid connection
var_dump($db);
mysql_select_db("my_db", $db) or die(mysql_error());
$query = "select visit_e_id, visit_e_type from visits";
$result = mysql_query($query, $db)
or die("Query failed: ".mysql_error()." Actual query: ".$query);
while($row=mysql_fetch_object($result))
{
....
}
Also ensure that you query syntax is correct and doesn't have misspelling or typos
This error is pretty simple and self-explanatory - a $result variable has unexpected type.
Thus, you have to so some debugging. Add var_dump($result); before and inside loop and study the output.
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
Really, it drive me crazy when I can't detect what error that happens. I can't handle it.
I managed to make a connection to MySQL, and check it out with:
$connection = mysqli_connect(HOST, USER, PASS, DB) or die('Could not connect!');
if($connection){
echo 'It's connected!';
}
Yeah, that say connected. Then, when I try a query, it fails without error reporting. I've tried do this to check if it fails:
$query = "SELECT $field FROM users WHERE id = ".$_SESSION['user_id'];
$result = mysqli_query($dbc, $query);
if($result){
echo 'Query OK';
}else{
echo 'Query failed';
}
The browser said: Query failed. So, there's an error in my query. Then I echoed the query out with this:
echo $query;
// Printed in the browser: SELECT firstname FROM users WHERE id = 1
Copy that value and use it in phpMyAdmin. It works. So, i guess an error occured in mysqli_query function. But i can't get the error message and so i don't know what's going on. I've tried this:
$result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
and this:
if(!$result){
echo mysqli_error($dbc);
}
Nothing happens. The browser just blank. Then, I tried to change this:
$result = mysqli_query($dbc, $query);
to this:
$result = mysqli_query($query);
Still nothing happens. What's going on? How can I know what error occured?
I run the server in Debian with phpinfo(): PHP Version 5.4.36-0+deb7u3
Guys read what they have posted, they are mixing the connections up.
$connection = mysqli_connect(HOST, USER, PASS, DB) or die('Could not connect!');
So this line should read:
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
With mysqli_ you need to pass the connection to a number of things that was not required in mysql_
Or you can switch your original db connect to $dbc
$dbc = mysqli_connect(HOST, USER, PASS, DB) or die('Could not connect!');
I hope this helps!
I ran this code and I got a Resource id #3 error where it should have showed the full movies table.
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("treehouse_movie_db") or die(mysql_error());
$data = mysql_query("SELECT * FROM movies")
or die(mysql_error());
echo $data;
This is not an error Your query is getting executed and you are getting appropriate resource from mysql_query() as it should be returned.
To get the response you have to use mysql_fetch_array() or mysql_fetch_assoc()
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("treehouse_movie_db") or die(mysql_error());
$data = mysql_query("SELECT * FROM movies")
or die(mysql_error());
while($row = mysql_fetch_assoc($data))
{
print_r($row);
}
SUGGESTION: mysql_* are no longer maintained .Try switching to mysqli_* or PDO
You're not getting an error, the MySQL API is just doing what you're asking it to: echoing the contents of $data, which is a MySQL query resource at this point. Extend the code to actually retrieve the results:
while($row = mysql_fetch_object($data))
var_dump($row);
And you'll see the output.
Note that the mysql_* API is deprecated since PHP 5.5 by the way.
Resourse id #3 means that the $data variable was used to open a resourse, it is not an error.
If you were to open another resourse, like a file, using:
$var=fopen('myfile','a+');
echo $var;
You would get Resourse id $4 as a result.
So to get the output you desire, you need to use a loop.
It is described in here.
I use this code , to log $_SERVER['REMOTE_ADDR']; to my small db
my issue is value never saved to db , cant figure what i missed in the code
Any tips ?
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs(REMOTE_ADDR,) VALUES ('$ip')";
}
echo $_SERVER['REMOTE_ADDR'];
?>
This should work. In addition to the other comments here, you had a comma (,) too much in your query.
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs (REMOTE_ADDR) VALUES ('$ip')";
mysql_query($sql);
}
initCounter();
?>
You aren't actually executing the query. You create the SQL but don't use mysql_query($sql)
You have a comma at this point in the SQL REMOTE_ADDR, <-- remove that
When you execute the query, use mysql_error() to test for an error message (and check the result of mysql_query() for a boolean false.
Finally I would suggest switching to MySQLi or PDO.
If that's you're full code... there is one thing missing you actually need to EXECUTE the query...
mysql_query($sql);
EDIT:
I have just noticed, you're connecting to the DB OUTSIDE of the function trying to run the Query... obviously it will fail as inside the function, it has no awareness of the DB connection.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
for some reason I get this:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/walterg/public_html/phptest.php on line 50
Warning: mysql_close(): 5 is not a valid MySQL-Link resource in /home/walterg/public_html/phptest.php on line 60
I'm just trying to do a simple sql query but i get errors
my code is :
$con = mysql_connect("localhost","walterg_kaden","nope");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("walterg_learning", $con);
$result = mysql_query("SELECT * FROM ralf");
while($row = mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($con);
2 simple rules for you to get it right
First. Always run your queries this way, at least until you adopt some more intelligent way to deal with queries:
$sql = "SELECT * FROM ralf";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
Second. Trust your eyes!
If database told you "there is no database selected" - so, it is. Means you are selecting wrong database in the earlier statement. Check spelling, database existence and such.
That's easy. You don't need no special knowledge for this - just a common sense.
larry, your sql is failing. it's always essential for debugging reasons - like the one you're experiencing today - to have a way of printing out any errors along the way through each sql execution a a fail safe so that if anything should go wrong you can make sure to print the error there and then as the error occurs so that you can locate and fix the problem right away
Your SQL query is failing. Use the mysql_error();. This will display the problem.
$result = mysql_query("SELECT * FROM ralf") or trigger_error(mysql_error());
There are Five steps to PHP database connections to follow:
// 1. Create a database connection
// (Use your own servername, username and password if they are different.)
// $connection allows us to keep refering to this connection after it is established
$connection = mysql_connect("localhost","root","OtlPHP07");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 2. Select a database to use
$db_select = mysql_select_db("widget_corp",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php
// 3. Perform database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned data
while ($row = mysql_fetch_array($result)) {
echo $row["menu_name"]." ".$row["position"]."<br />";
}
?>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>
There must be two reasons.....
1. may be you have mistaken in assigning table naem while using select query or while assigning host,username,password,db
2. you must use this before while loop
if(mysql_num_rows($result)>0){ while($row = mysql_fetch_array($result))
{
echo $row['name'];
} }
hope that solves your problem
This will tell you why your query is failing:
$result = mysql_query("SELECT * FROM ralf") or die(mysql_error());
What is wrong, when you connect to the DB on the LINE BEFORE THE QUERY, and you still get "MySQL server has gone away"?
check this example code:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
$ids[] = $data[id];
}
foreach ($ids as $id) {
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
mysql server is gone away, i get that in the foreach loop.
BTW i need to connect in the foreachloop, because it may take along time before it finds something to update (like 1-2 minutes), and then for sure i will get mysql server has gone away.
I assume your issue is that the script may execute for a very long time before sending the first UPDATE query.
You should check the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"
You can also try to piece of code to do a reconnect:
if (!mysql_ping ($conn)) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close($conn);
$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);
}
Combining with your code it would be:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
if (!mysql_ping ()) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close();
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
}
$ids[] = $data['id'];
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
We got that error this week at work here is the official documentation from MySQL : http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
This section also covers the related Lost connection to server during query error.
The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection.