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).
Related
I have several stored procedures that I am calling via PDO in PHP. I was hoping to be able to handle errors by performing a ROLLBACK, but I still want to be able to use PHP to retrieve and handle the last error in the procedure. I have tryed using PDO::errorCode() and PDO::errorInfo(), but that does seem to be a legitimate solution, I think because I am already handling the errors in my stored procedures.
When I call one of the stored procedures via command line and then call SHOW ERRORS I get a nice result set with the error status, code and message, but if I call SHOW ERRORS in PDO after executing the stored procedure, I get no results. I also get no result from SHOW ERRORS in command line if I call show errors inside the stored procedure.
I would use GET DIAGNOSTICS, but the MySQL server I am developing for is on a hosted cPanel that I don't have control over updating and it is version 5.5.
Is there some other option I could use or another route I should be taking?
Like I said, I have several stored procedures I want to handle errors, but I can't even get this to work on a simple stored procedure:
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
SELECT *
FROM bunnies;
END
Update: My PHP code was in an object, so I copied and simplified the code to post per Barmar's request and when I tried the simplified code, I found that SHOW ERRORS does indeed work with PDO when prepared and executed after the function is prepared and executed.
My object was a little complicated (I wrote it a while back before I knew much about PHP OOP), so I simplified it as well and now it works! I think the connection was being closed in between calls and now that the code is simpler, I am having no problems with calling SHOW ERRORS in it.
Here's the simplified PHP code I used to test, in case anyone has had issues getting this to work:
$host = '***';
$user = '***';
$pass = '***';
$schema = '***';
$connection = new PDO('mysql:host=' . $host . ';dbname=' . $schema . ';', $user, $pass);
$statement = $connection->prepare('CALL test()');
$statement->execute();
$statement = $connection->prepare('SHOW ERRORS');
$statement->execute();
echo var_dump($statement->fetchAll());
$statement = null;
$statement = null;
$connection = null;
Make sure you use the same PDO connection object to execute the original queries and to retrieve the errors. Each connection has its own error state.
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.
I am rather new to the PDO library, so I apologize for my inexperience. I am writing a class that uses the PDO library to build and execute queries and return the results, no matter what they are.
Within the class, I detect whether there is an open connection to a database, and if it is the same as the one being configured, it uses this one instead. This is really easy to do using the MsSQL library as the PDO::getAttribute() function returns 'CurrentDatabase' and 'SQLServerName', so I can just apply a condition like so:
if(!empty($this->PDO)){
// Get the current connection information
$current_connection = $this->PDO->getAttribute(PDO::ATTR_SERVER_INFO);
// Return if the connection is the same
if($this->connection_parameters['hostname']==$current_connection['SQLServerName']&&$this->connection_parameters['database']==$current_connection['CurrentDatabase']){
return;
}
}
However, when it comes to MySQL, the data returned from PDO::getAttribute is completely different and I cannot seem to get the database name from the current connection.
Does any body know a function or method to get the currently connected database of a MySQL connection using the PDO library in PHP?
I order to connect to both MySQL and MsSQL, you must have 2 connections. However, changing the database on a live connection is very simple.
The following simply checks if a PDO instance already exists and whether or not it is using the required database. If so then it continues with this connection, if not it changes the database.
// Test if the PDO object already exists
if(!empty($this->PDO)){
// If connection is the same then select the database
if($this->connection_engine==$this->PDO->getAttribute(PDO::ATTR_DRIVER_NAME)){
// Get the current database in use
$database = $this->PDO->query("SELECT {$this->select_db_function}");
$database = $database->fetchAll(PDO::FETCH_NUM);
$database = $database[0][0];
// If the current database matches the new database then return
if($database==$this->connection_parameters['database']){
return;
}
}
}
I see no point in looking for the opened connection and - especially - in checking for the current database.
Why can't you just open the connection, select the database for it and then use this connection all the time throughout your class - just like everyone does?
See comments on the MySQL manual page for 'USE database'
I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.
When I open a MySQL connection in PHP with just PHP's built-in MySQL functions, I do the following:
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
//queries etcetera
mysql_close($link);
When I open a connection with PDO, it looks like this:
$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries
Do I have to explicitly close the connection like I do with mysql_connect() and mysql_close()? If not, how does PHP know when I'm done with my connection?
TIA.
Use $link = null to let PDO know it can close the connection.
PHP: PDO Connections & Connection Management
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
PDO does not offer such a function on its own. Connections via PDO are indirectly managed via the PDO objects refcount in PHP.
But sometimes you want to close the connection anyway, regardless of the refcount. Either because you can not control it, need it for testing purposes or similar.
You can close the Mysql connection with PDO by running a SQL query. Every user that is able to connect to the Mysql server is able to KILL at least its own thread:
/*
* Close Mysql Connection (PDO)
*/
$pdo_mysql_close = function (PDO $connection) {
$query = 'SHOW PROCESSLIST -- ' . uniqid('pdo_mysql_close ', 1);
$list = $connection->query($query)->fetchAll(PDO::FETCH_ASSOC);
foreach ($list as $thread) {
if ($thread['Info'] === $query) {
return $connection->query('KILL ' . $thread['Id']);
}
}
return false;
};
$pdo_mysql_close($conn);
Related Mysql Documentation:
13.7.5.30. SHOW PROCESSLIST Syntax
13.7.6.4. KILL Syntax
Related Stackoverflow Questions:
PHP PDO close()? (Apr 2012)
When the PHP script finishes executing, all connections are closed. Also you don't have to explicitly close your connection with mysql_close().
You can also limit your connections to within local functions. That way the connection is closed as soon as the function is completed.
Well seeing as the $link for the PDO is assigned an object, PHP would set that as null as soon as the script runs so that it's no longer an object. Therefore you could just do:
$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries
$link = null;
http://uk3.php.net/pdo
From what i gather i could not see anyway to close it in the php manual, and examples of scripts i quickly looked at never closed the connection in anyway from what i could see.