Autoreconnect class for database in php - php

I am developing a class for Database access and query.
If database is accessible it is working correctly, But problem comes when somehow database is restarted.
Below is the code for library and its users code.
It is able to reconnect with database, but unable to select database. I have tried for 2,5 retry attempts from select_from_db function. But its throwing error Unable to select database test MySQL server has gone away. I am using Windows machine and in sleep time i am executing below command for restarting mysql.
net stop wampmysqld
net start wampmysqld
Please let me know for your suggestion and answers, so that i can improve on it.
<?php
class database {
private $host;
private $user;
private $pswd;
private $name;
private $db_handle;
private $error_msg;
function __construct($db_host, $db_user, $db_pswd, $db_name=NULL){
$this->host = $db_host;
$this->user = $db_user;
$this->pswd = $db_pswd;
$this->name = $db_name;
$this->db_handle = NULL;
$this->error_msg = NULL;
}
function connect(){
if(!is_null($this->db_handle)){
return True;
}
echo "Trying connection..\n";
$this->db_handle = mysql_connect($this->host, $this->user, $this->pswd);
if(!$this->db_handle){
$this->db_handle = NULL;
$this->error_msg = "Unable to connect to database : ".mysql_error();
return False;
}
else{
echo "\nconnected to database successfully!\n";
}
echo $this->name. "\n";
if(!is_null($this->name)){
$result = mysql_select_db($this->name, $this->db_handle);
if(!$result){
$this->db_handle = NULL;
$this->error_msg = 'Unable to select database '.$this->name.' '.mysql_error();
return False;
}
else{
echo "\nselected database successfully!\n";
}
}
return True;
}
function select_from_db($query, $retry=True){
if(!$this->is_connected()){
$result = $this->connect();
echo " 45 : $result\n";
if(!$result)
return $result;
}
echo " executing query \n";
$result = mysql_query($query, $this->db_handle);
if(!$result){
if(stristr(mysql_error(), 'MySQL server has gone away') === False){
$this->error_msg = "Unable to execute query ".mysql_error();
}
else{
if($retry){
$this->db_handle = NULL;
$result = $this->connect_wait(30,5);
return $this->select_from_db($query, False);
}
}
}
echo mysql_error();
echo " returning result $result query \n";
return $result;
}
function insert_to_db($query){
$result = $this->select_from_db($query);
if(!$result)
return $result;
if(stripos($query, 'insert into') !== False){
return mysql_insert_id($this->db_handle);
}
return $result;
}
function is_connected(){
if(is_null($this->db_handle))
return False;
return True;
}
function connect_wait($seconds_to_wait=30, $no_iterations=-1){
$result = $this->connect();
for($counter = 0; ($counter < $no_iterations) && !$result; $counter++){
echo "** $counter \n";
echo "\n$result waiting\n";
sleep($seconds_to_wait);
$result = $this->connect();
echo "\n$result\n";
}
return $result;
}
function disconnect() {
if(!is_null($this->db_handle)){
mysql_close($this->db_handle);
$this->db_handle = NULL;
}
}
function get_error() {
return $this->error_msg;
}
function __destruct() {
$this->disconnect();
}
}
// Connection to database machine
$db_host = 'localhost';
$db_user = 'root1';
#$db_pswd = 'rTpswd$567';
$db_pswd = '';
$db_name = 'test';
$db_table = 'user_login_info';
$db_obj = new database($db_host, $db_user, $db_pswd, $db_name);
if($db_obj->connect()){
echo "Connected";
sleep(20);
echo "Querying";
$query = "select * from $db_table";
$result = $db_obj->select_from_db($query);
if(!$result){
echo mysql_error();
die($db_obj->get_error());
}
while($row = mysql_fetch_assoc($result)){
echo "{$row['user_login_name']} {$row['user_password']}\n";
}
$db_obj->disconnect();
}
?>

PDO is a good library, you don't have to write your own !
You can add a class https://gist.github.com/extraordinaire/4135119 and use it to automatically reconnect when the database is away.

Related

PHP MySQL Only Printing Last Row in Query

Is it possible to get different output when you run the exact same query from PHP vs. PHPMyAdmin? When I run
$sql = "SELECT IF(PersonA=200, PersonB, PersonA) AS Person
FROM People
WHERE PersonA=200 OR PersonB=200;";
I get the correct output from PHPMyAdmin but a different (incorrect) result from my PHP code above. The following is my SQL class I use.
<?php
class SQLQueryExecutor {
private $queryString;
private $conn;
private $db;
private $host;
private $username;
private $password;
public function __construct($queryString, $db, $host, $username, $password) {
$this->queryString = $queryString;
$this->conn = NULL;
$this->db = $db;
$this->host = $host;
$this->username = $username;
$this->password = $password;
}
// make connection to mysql database
public function makeConnection() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->db);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
// execute query
public function executeQuery() {
if ($this->conn != NULL)
{
$result = mysqli_query($this->conn, $this->queryString);
$rows = Array();
if ($result !== False) // resource returned?
{
while($row=mysqli_fetch_assoc($result))
{
$rows= $row;
}
return $rows;
}
}
return NULL;
}
// close sql connection
public function closeConnection() {
mysql_close($this->conn);
}
} // class
?>
I call this class as follows...
$user = $_GET['User_ID'];
$sql = "
SELECT IF(PersonA=$user, PersonB, PersonA) AS Person
FROM People
WHERE PersonA=$user OR PersonB=$user;";
$newSQLQueryExecutor = new SQLQueryExecutor($sql, "blah","blah", "blah", "blah");
$newSQLQueryExecutor->makeConnection();
$rows = $newSQLQueryExecutor->executeQuery();
$friends = Array("friends" => $rows);
$newSQLQueryExecutor->closeConnection();
print_r($friends);
The PHPMyAdmin prints all the correct rows but the PHP only prints the very last row.
Here is your issue, a mistake in the executeQuery() method
public function executeQuery() {
if ($this->conn != NULL) {
$result = mysqli_query($this->conn, $this->queryString);
$rows = Array();
if ($result !== False) { // resource returned?
while($row=mysqli_fetch_assoc($result)) {
$rows[] = $row;
// amended ^^
}
return $rows;
}
}
return NULL;
}

PHP MySQLI OOP not work

I want to ask help for my MySQLI OOP. My MySQLI Class look like this:
Class DB {
Private $connection;
Public Function __construct($host = "localhost", $user = "root", $password = "", $db = "social_network") {
$this->host = $host;
$this->db = $db;
$this->user = $user;
$this->password = $password;
$this->connection = #new mysqli($this->host, $this->user, $this->password);
$this->connection->set_charset("UTF-8");
if($this->connection->connect_errno > 0){
die('Tietokantapalvelimeen ei saada yhteyttä [' . $this->connection->connect_error . ']');
} else {
if(!$this->connection->select_db($db)) {
die('Tietokantaan ei saada yhteyttä: ' . $this->connection->error);
}
return $this->connection;
}
}
Public Function connect() {
if(!$this->connection){
return $this->connection;
}
return true;
}
Public Function disconnect() {
if($this->connection){
$this->connection->kill($this->connection->thread_id);
$this->connection->close();
}
return true;
}
Public Function query($sql) {
return $this->connection->query($sql);
}
Public Function result($sql) {
$query = $this->connection->query($sql);
if($query){
$result = array();
$i = 0;
while($row = $query->fetch_object()){
$result[$i] = $row;
$i++;
}
return $result;
} else {
return print $this->connection->error;
}
}
Public Function escape_string($sql) {
return $this->connection->real_escape_string($sql);
}
Public Function __destruct() {
$this->disconnect();
}
}
Example result:
$DB = new DB($_CONFIG['host'], $_CONFIG['user'], $_CONFIG['password'], $_CONFIG['db']);
$row = $DB->result("SELECT username, password FROM users WHERE username = T0niiiiii LIMIT 1");
print $row['username'];
I get error "Unknown column 'T0niiiiii' in 'where clause' ".
So what is wrong? How i fix that? Or anyone know ready MySQLI OOP?
If you don't wrap the value with apostrophes, MYSQL will 'think' you're referencing a column.
This should be your code:
$DB->result("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
You didn't even need to ask in here, the error message says it all.
And about retrieving the row, you could do this:
$query = $DB->query("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
foreach ($query->result() as $row)
{
echo $row->username;
echo $row->password; //Never echo the password, this is just for testing :P
}

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

Displaying data using MySQL class in PHP

I know how to display data without using class, but i have been asked to use mysql class instead. It seems that i have to initiate the class and just use the written functions, but whatever i try to display - it doesn't work. All i am getting is "Resource id #14", which means that everything should be good with the connection. Please help!
This is a part of the MySQL class:
class SQL //MySQL
{
var $link_id;
var $query_result;
var $num_queries = 0;
function connect($db_host, $db_username, $db_password, $db_name = '', $use_names = '', $pconnect = false, $newlink = true) {
if ($pconnect) $this->link_id = #mysql_pconnect($db_host, $db_username, $db_password);
else $this->link_id = #mysql_connect($db_host, $db_username, $db_password, $newlink);
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
if ($this->link_id){
if($db_name){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
}
} else die(mysql_error());// = "Can't connect to mysql server";
}
function db($db_name) {
if ($this->link_id){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
} else die(mysql_error());// = "Can't connect to database";
}
function query($sql){
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result){
++$this->num_queries;
return $this->query_result;
} else {
$error = "
<pre>
QUERY: \n {$sql} \n\n
ERROR: <span style=\"color:red\">" . mysql_error() . " </span>
</pre>
";
die($error);
}
}
function result($query_id = 0, $row = 0, $field = NULL){
return ($query_id) ? #mysql_result($query_id, $row, $field) : false;
}
function fetch_row($query_id = 0){
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
function fetch_array($query_id = 0){
return ($query_id) ? #mysql_fetch_array($query_id) : false;
}
function fetch_assoc($query_id = 0){
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
function num_rows($query_id = 0){
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
....
and my php code:
<?php
require_once('C:/wamp/www/smarty-3.1.21/libs/Smarty.class.php');
include('C:/wamp/www/smarty-3.1.21/libs/Mysql.class.php');
$smarty = new Smarty();
$smarty->enableSecurity();
$smarty->setTemplateDir('C:\wamp\www\forum\templates');
$smarty->setCompileDir('C:\wamp\www\forum\templates_c');
$smarty->setConfigDir('C:\wamp\www\forum\configs');
$smarty->setCacheDir('C:\wamp\www\forum\cache');
$db = new SQL();
$db->connect('localhost','root','','job', '', false, true);
$db->db('job');
$sql = "SELECT * FROM job";
$db->query($sql);
$output = $db->query_result;
$result = $db->fetch_row();
$smarty->assign('rez', $result);
$smarty->assign('output', $output);
$smarty->display('index.tpl');
?>

SQL Query can not run after stored-procedure call in php

In My php code i call stored-procedure before Normal SQL (link : SELECT * FROM TABLE;) Query run. for that stored-procedure run but Normal SQL can-not run. I use mysql_query() in both case. but when i run normal SQL it run both time.
I have a class dataManager that have the mysql_query()
here is my code :
require_once 'DL/DataManager.php';
require_once 'utils/Utils.php';
require_once 'DL/class/event/Event.php';
$Utils = new Utils();
$obj = new Event();
$result = array();
$result = $obj->get_all_event_data("NULL"); //Query = "CALL events_all_data(" . $ID . ");";
echo date("y-m-d h:i:s")."<br />";
echo $Utils->getString_UserName_ByUserID( "23" )."<br />"; // Not Run Query = SELECT `USER_NICK` FROM `USER_INFO` WHERE `USER_ID` ='".$string ."';";
DataManager.php
public function openConnection()
{
$this->connection = mysql_connect($this->HostName, $this->UserName, $this->PassWord);
if (!$this->connection)
{
return mysql_error();
}
mysql_select_db($this->DataBase);
return $this->connection;
}
execute sql query
public function retrieveData($Query = "")
{
//$Query = mysql_real_escape_string($Query);
//echo "DB retriveData query : ".$Query. " <br />";
$data = mysql_query($Query);
$num_rows = mysql_num_rows($data);
//echo "db ret number : ".$num_rows." asdas: ". "\n";
if($num_rows)
{
$this->Data = array();
//$i = 0;
while ($mat[] = mysql_fetch_row($data));
//echo $mat[$i++][2]."<br />";
$this->Data = $mat;
//print_r($this->Data);
//$result = $this->getArrayTranspose($mat);
}
else
{
$this->Data = NULL;
}
//return $result;
}
Connection Close
public function closeConnection()
{
if(!$this->connection)
{
mysql_close ();
return ;
}
else if($this->connection == NULL)
{
mysql_close ();
return ;
}
else if(!isset($this->connection))
{
mysql_close ();
return ;
}
else if(is_resource($this->connection))
{
mysql_close($this->connection);
return ;
}
else
{
//mysql_close();
}
}
In your code you did not mention anywhere that what is $string
Try to run query like this to get error code.
$mat=mysql_query($query) or die (mysql_error());
Give it a try.
Mysql Error is: Commands out of sync; you can't run this command now

Categories