Warning: mysql_query(): 3 is not a valid MySQL-Link resource - php

I got this odd error and I can't figure out where it came from:
Warning: mysql_query(): 3 is not a valid MySQL-Link resource in (...)
What's up with the 3? I don't get it. Has anyone experienced this error themselves?

PHP uses resources as a special variable to hold links to external objects, such as files and database connections. Each resource is given an integer id. (Documentation)
Failed Connections
If the database connection fails you'll likely get a "Specified variable is not a valid MySQL-Link resource" error, as Dan Breen mentioned, since the variable that is supposed to hold the resource is null.
$link = mysql_connect('localsoth','baduser','badpass'); // failed connection
$result = mysql_query("SELECT 1", $link); // throws error
Since you're getting a specific resource ID in the error message, the database connection likely closed unexpectedly for some reason. Your program still has a variable with a resource ID, but the external object no longer exists. This may be due to a mysql_close() call somewhere before the call to mysql_query, or an external database error that closed the connection.
$link = mysql_connect();
mysql_close($link);
// $link may still contain a resource identifier, but the external object is gone
mysql_query("SELECT 1", $link);
Reusing Connections
An issue with the mysql extension and mysql_connect() is that by default if you pass the same parameters in successive calls, it will re-use the existing connection rather than create a new one (Documentation). This can be fixed by passing true to the $new_link parameter.
I encountered this myself on a test system where the data from two separate databases in production were combined on to one test server, and in testing the mysql_xxx() function calls walked over each other and broke the system.
$link1 = mysql_connect('localhost','user','pass'); // resource id 1 is given
$link2 = mysql_connect('localhost','user','pass'); // resource id 1 is given again
mysql_close($link2); // the connection at resource id 1 is closed
mysql_query("SELECT 1", $link1); // will fail, since the connection was closed
Using $new_link:
$link1 = mysql_connect('localhost','user','pass'); // resource id 1 is given
$link2 = mysql_connect('localhost','user','pass', true); // resource id 2 is given
mysql_close($link2); // the connection at resource id 2 is closed
mysql_query("SELECT 1", $link1); // the connection at resource id 1 is still open
Edit:
As an aside, I would recommend using the MySQLi extension or PDO instead, if possible. The MySQL extension is getting pretty old, and can't take advantage of any features past MySQL version 4.1.3. Look at http://www.php.net/manual/en/mysqli.overview.php for some details on the differences between the three interfaces.

I also had this problem. In examining my code I found I had an include of a script that closed the connection, so when php tried to close it again we got the error.
To solve this, just check if the connection is open before trying to close it:
instead of:
mysql_close($con);
Do this:
if( gettype($con) == "resource") {
mysql_close($con);
}

I had this error just a minute ago, it was because i was including a my database connection file which had a close connection function at the bottom. Get rid of your close connection and your be fine!

It sounds like you might be getting an error while trying to connect to the database, and the mysql handle is not actually a valid connection. If you post more code, like how you're connecting to the database, that would be more helpful. Make sure you're checking for errors, too.

Related

mysqli_query(): Couldn't fetch mysqli

I've been checking on this error with no solutions specific to my code. I have connected to mysql server using the mysqli_connect() call. then passed the connection result to a $_SESSION to have it available over the whole website - as i normally do in all my other projects, But for some reason i keep getting the error:
"mysqli_query(): Couldn't fetch mysqli"
There is the code that generates the error:
if(!isset($_GET['sortBy']))
{
$listSQL = "SELECT * FROM '".$_SESSION['WorkTable']."'";
}
else
{
$listSQL = "SELECT * FROM '".$_SESSION['WorkTable']."' where ".$_GET['sortBy']."='".$_GET['sortBy']."'";
}
//get Contacts From DB
if(!empty(mysqli_query(#$_SESSION['IMWEDBcxn'],$listSQL)))
Here is the connection class code...
if(!empty($cxn))
{
$_SESSION['WorkTable'] = $dbTable;
$_SESSION['IMWEDBcxn'] = $cxn;
}
Anything I'm missing here?
As stated by Ivan Solntsev, do not store a connection handler in a user's session for 2 obvious reasons :
1- Handlers can not be serialized.
2- Anything you store in a user's session (using $_SESSION), would only be available under that user's scope. I suggest you read more about sessions and PHP, $_SESSION is not a way to store data over sessions.
So doing something like :
$connect = mysqli_connect("...");
$_SESSION["dbconnection"] = $connect;
mysqli_query($_SESSION["dbconnection"], $query);
IS WRONG!
If you want a persistent connection, to avoid reconnecting on each DB query, read about MySQLi and Persistent connections : http://php.net/manual/en/mysqli.persistconns.php . If you are running on a PHP version under 5.3, I'd recommend using PDO (which I'd recommend regardless of the PHP version you're using).

Mysqli_result availability

Can you still use a mysqli_result object after you have closed the mysqli connection that produced it? For instance, I am creating a PHP object with a method that opens a mysqli connection, performs a query, stores the result into a parameter, then closes the connection. Will this work or should I fetch_all() the result into an array and then close the connection?
I can find nothing in the documentation or elsewhere online that answers this question. Perhaps that is because it is mind-boggingly obvious to everyone else but it is not to me.
Yes. By default, mysqli runs queries with the option MYSQLI_STORE_RESULT, which means it copies the result set to the client (into the memory of the PHP driver). Therefore when you "fetch" from a mysqli result, you're really just looping over the result set that has already been completely fetched from the MySQL Server. And if you close the connection, the driver keeps that data.
Here's a quick code example to demonstrate:
$con = new mysqli(...);
sleep(10);
/* go run SHOW PROCESSLIST in a MySQL shell to see the connection */
$sql = "SELECT SLEEP(10) FROM test.foo ";
$result = $con->query($sql);
/* observe the query running in SHOW PROCESSLIST */
$con->close();
sleep(10);
/* now go look at SHOW PROCESSLIST to verify the connection is gone */
print_r($result->fetch_all());
/* Hey! I got the data anyway */

Connecting to a mysql database without keeping details in the script

I am attempting to create a separate login file for database connections as I am not too fond of having all the access details on each page that requires database access.
I have created a separate file on my server that contains the variables required for a successful login and then use the;
include_once('path_to_file/filename.php');
to get the variables and then use;
$dbconnection = mysqli_connect("$hostname","$username","$password","$database") or die ("Could not connect to the server");
but the connection fails every time. I tried including the connection script in the file I am attempting to include but then I get this message:
Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)
I'm not really sure how to fix this, but every page in my server more or less access the database and I think it has to be a security risk having login details replicated everywhere!
Anyone have any suggestions or alternatives?
databaseloging format is:
<?php
# parameters for connection to MySQL database
$hostname="hostname";
$database="databasename";
$username="username";
$password="password";
?>
P.S. I have also tried require and got the same result.
Also when using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
http://www.php.net/manual/en/function.mysql-connect.php

Fetch data from second database frequently while connection to first database is always available

I m working on old existing project which uses mysql function for database operation. The existing system connects to the database, say cdcol. The connection to this database is available through site wise.
Now I want to fetch data from another database say crawlerdb, assign fetched data to an array and close connection to this database. The connection to second database is inside a function say GetAccess, and each time the extra data needed, the function is called, data fetched and connection closed to the second database.
All I want is connection to first database should be available every time.
The problem I m facing is. If i don't close connection to second database. Then mysql query used after calling the function GetAccess, still search items from second database, because the connection to second database is active. If I close the connection to second database, still the query doesnot work. Following code explains my situation.
<?php
//$conn1 is permanent connection that is used sitewise.
$conn1=mysql_connect("localhost","root","",true) or die(mysql_error());
mysql_select_db("cdcol",$conn1) or die(mysql_error());
echo "1. Current Database = ".mysql_current_db();//prints cdcol
echo "<Br> Function Returned Value = ".GetAccess();
echo "<Br>2. Current Database = ".mysql_current_db(); //In GetAccess function, which is called above if mysql_close($conn2) is used, the mysql_current_db() returns empty value.
//A FUNCTION TO GET EXTRA DATA FROM SECOND DATABASE
function GetAccess(){
$conn2=mysql_connect("localhost","root","",true) or die(mysql_error());
mysql_select_db("crawlerdb",$conn2) or die(mysql_error());
$test=mysql_query("select * from tbllensinfo",$conn2); //here i have used $conn2 as link identifier
$var= mysql_num_rows($test);
mysql_close($conn2);
return $var;
}
//FUNCTION TO IDENTIFY WHICH DATABASE IS CURRENTLY BEING USED
function mysql_current_db() {
$r = mysql_query("SELECT DATABASE()") or die(mysql_error());
return mysql_result($r,0);
}
$res=mysql_query("select * from cds"); //here link identifier $conn1 is not used, i cant change this code because there are several 100s codes, so not possible to change in all of them. Everything will work if $conn1 is used here though
echo "<br>".mysql_num_rows($res);
?>
NOTE:
The two database are hosted on same server, but database users are different, one of which have no access to other database.
So in short What I need is I need to fetch data from second database frequently while connection to first database is always available.
Any help will highly be appreciable, thanks !
Thanks
Sharmila
The mysql functions, such as mysql_query, all have an optional resource parameter identifying the database connection to use. If you omit this second parameter, the functions use the most recently opened connection. That is, they use the connection resulting from the most recent call to mysql_connect. It's considered the most recent result even if you have closed it already.
(Global variable! Let's party like it's 1999!)
If you're going to use more than one connection with mysql calls in your program, you must specify the resource parameter in all mysql_* calls in your program.
Please consider switching to PDO or mysqli. The PHP people have been trying to get rid of this mysql API for years, partly because of this problem, and mostly because it has serious insecurities.

mysql_close(): 5 is not a valid MySQL-Link resource in C:\wamp\www\Includes\footer.php on line 4

Everyth worked fine, it just decided to stop working and it ruined my whole project and Im at standstill.
This is error:
mysql_close(): 5 is not a valid MySQL-Link resource in
C:\wamp\www\Includes\footer.php on line 4
This is footer.php
<?php
//close connection
if (isset($dbh)); {
mysql_close($dbh);
}
?>
This is connect.php
//set constants
require("quick.php");
//database connection
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$dbh) { //check connection
die("Cannot conect! to database ");
}
//selecting database
$db_select = mysql_select_db(DB_NAME, $dbh);
if (!$db_select) { //check connection
die("Cannot connect to database ");
}
?>
Basically whenever I try to quit mysql this error shows.
And it all worked fine not long ago.
Try this instead:
if (isset($dbh) && is_resource($dbh)) {
mysql_close($dbh);
} else {
mysql_close();
}
From manual:
mysql_close() closes the non-persistent connection to the MySQL server
that's associated with the specified link identifier. If
link_identifier isn't specified, the last opened link is used.
Maybe he's having few connections.. Who knows..
Somewhere, within your page, there is an assignment that puts $dbh = 5; that overrides your database connection. That is the cause for the error. Search for any assignments to that variable between your database opening and your footer, and you've found your problem.
Note: I wouldn't be that worried about the connection being open as some other commenters here, since if it's not a persistant connection, it will anyway be closed at the end of the script, so I don't see how that would be ruining your whole project. Your code tries to close it at the footer which is not much different than letting it close itself. From the manual:
Using mysql_close() isn't usually necessary, as non-persistent open
links are automatically closed at the end of the script's execution.
See also freeing resources.
All the mysql_* functions will assume "the last connection you opened" if you don't specify a connection. This is useful because you don't have to keep track of it like you do for other libraries. Most likely here you are overwriting the variable $dbh somewhere. Personally I'd use a variable like $_connection if I use one at all.
So just mysql_close() will be enough to close the connection. You need only worry about this kind of thing if you are handling more than one connection at a time.

Categories