I'm the developer of a PHP comments script which is designed to be included into the body of the users' websites. The script has its own database connection and currently uses the 'MySQL' extension. To make the script easier to integrate, I preserve the website's existing database connection (if there is one) by adding these two lines before connecting to the script's own connection ..
@$original_database = mysql_query('SELECT DATABASE();');
@$original_database = mysql_result($original_database, 0);
.. then after my script has finished I select the original database ..
if (!empty($original_database)) {
@mysql_select_db ($original_database);
}
This is working fine at the moment. However many websites are (quite rightly) starting to use the newer extensions such as 'MySQLi' and 'PDO', and this makes it harder to preserve the existing database connection because for instance 'MySQLi' will complain that the connection is through 'MySQL'. Can you recommend the best way to deal with this? If it makes any difference, I plan to switch from 'MySQL' to 'MySQLi' in the near future, but obviously I will still have the same problem.
Always use 'MySQLi'
function custom_mysqli_connect(){
$GLOBALS['db_connect']=false;
$GLOBALS['db_connect']=@mysqli_connect(HOSTNAME, USERNAME, PASSWORD);
if($GLOBALS['db_connect']==false){
echo("Unable to connect to the database");
}
if(!@mysqli_select_db($GLOBALS['db_connect'], DATABASE)){
echo("Unable to select database");
}
mysqli_query($GLOBALS['db_connect'],'SET NAMES UTF8');
}
Call custom_mysqli_connect() once
Make your queries:
$query_1 = "SELECT * FROM table";
if($results=@mysqli_query($GLOBALS['db_connect'], $query_1)){
$array=array();
while($result=mysqli_fetch_assoc($results)){
$array[]=$result;
}
mysqli_free_result($results);
}
When your are done
@mysqli_close($GLOBALS['db_connect']);
There is plenty of other ways to fetch the results
mysqli_ result:: fetch_ all
mysqli_ result:: fetch_ array
mysqli_ result:: fetch_ assoc
mysqli_ result:: fetch_ field_ direct
mysqli_ result:: fetch_ field
mysqli_ result:: fetch_ fields
mysqli_ result:: fetch_ object
mysqli_ result:: fetch_ row