SQL Query can not run after stored-procedure call in php - 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

Related

Autoreconnect class for database in 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.

PHP - Getting: Commands out of sync; you can't run this command now

I know that there were hundreds of similar questions, I have tried everything and nothing really worked for me.
I have got this function that is calling stored procedure in my MariaDB. This is returning array.
<?
class MyClass {
protected static $connection;
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
self::$connection = new mysqli(SERVERNAME,USERNAME,PASS,DBNAME);
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
return self::$connection;
}
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
public function quote($value) {
$connection = $this -> connect();
return $connection -> real_escape_string($value);
}
public function CallStoredProc($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query,MYSQLI_USE_RESULT); //,
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
$result->free();
return $rows;
}
function StoreProcessed($Name,$Price){
//escape
$Name = $this->quote($Name);
$Price= $this->quote($Price);
$SQL = "INSERT INTO Result (`Name`,`Price`) VALUES ('$Name','$Price');";
$result = $this->query($SQL);
}
//the function I am using for processing:
function Compare($ID) {
$query = "CALL MyProcedure($ID);";
$result =$this->CallStoredProc($query);
/*After the array is returned I am looping trough each element of array
and storing this in DB with another function. */
$Table = "<table>";
foreach ($result as $key=>$val)
{
$Name = $result[$key]["Name"];
$Price = $result[$key]["Price"];
$this->StoreProcessed($Name,$Price);
//This is where the Commands out of sync is returned
$Table = $Table. "<tr>
<td>$Name</td>
<td>$Price</td>
</tr>";
}
$Table = $Table. "</table>";
return $Table;
}
}
My php file then looks like this:
<?
$auto = new MyClass();
$table = $auto->Compare(14);
echo $table;
?>
I am using MYSQLI_USE_RESULT, after the array is filled, I am using the mysqli_free_result as well. What else should I do?
Many thanks!
I've found answer here . Just added this function:
function free_all_results(mysqli $dbCon)
{
do {
if ($res = $dbCon->store_result()) {
$res->fetch_all(MYSQLI_ASSOC);
$res->free();
}
} while ($dbCon->more_results() && $dbCon->next_result());
}
And I called it before returning the results:
public function CallStoredProc($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query); //,
mysqli_store_result($connection);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
$this->free_all_results($connection);
return $rows;
}

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
}

php error happen Warning: mysqli::close(): Couldn't fetch mysqli error in php [duplicate]

This question already has answers here:
PHP Warning: mysqli::query(): Couldn't fetch mysqli [duplicate]
(2 answers)
Closed 5 years ago.
I have problem to make a code for connecting to DB and after that close the connections.
my DB class is below:
class DataBase {
private $conn;
private $info;
private $db;
public function __construct ($servername=DB_SERVER, $user=DB_USER, $pass=DB_PASS, $db=DB_DATABASE) {
$this->db = $db;
$this->conn = new mysqli($servername,$user,$pass, $this->db);
if (!$this->conn)
{
if ($this->conn->connect_error) {
$this->info = "ERROR CODE=DB100: Connection failed <br> " . $conn->connect_error;
$this->close();
echo $this->getInfo();
}
else {
$this->info = "ERROR CODE=DB101: Connection failed <br> ";
$this->close();
echo $this->getInfo();
}
}
}
public function getInfo () {
return $this->info;
}
// send sql to database
public function sendQuery ($sql, $numr=null, $start=null) {
if ($numr) {
if ($start)
$sql .= " LIMIT $start, $numr";
else
$sql .= " LIMIT $numr";
}
$this->conn->set_charset("utf8");
$result = $this->conn->query($sql);
if ($result == true) {
return $result;
}
else {
$this->info = "ERROR CODE=DB102: Sql query not work <br>".$this->conn->error;
$this->close();
echo $this->getInfo();
return false;
}
}
public function sendQueryNoneCahrSet ($sql, $numr=null, $start=null) {
if ($numr) {
if ($start)
$sql .= " LIMIT $start, $numr";
else
$sql .= " LIMIT $numr";
}
$result = $this->conn->query($sql);
if ($result == true) {
return $result;
}
else {
$this->info = "ERROR CODE=DB103: Sql query not work <br>".$this->conn->error;
$this->close();
echo $this->getInfo();
return false;
}
}
// send sql query safe to avoid sql injection.
public function getConn () {
return $this->conn;
}
public function getDataBase (){
return $this->db;
}
// This method close the connection
public function close () {
$this->conn->close();
}
function __destruct() {
$this->close();
}
}
and when I run this code:
$con = #new DataBase();
$r = $con->sendQuery($sql);
$con->close();
I got this error:
Warning: mysqli::close(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\automasion\admin\protected\componets\database.php on line 102
program run correctly and set data into DB but this Error happen.
error point to:
$this->conn->close();
in my DB Connection code.
In your constructor you created a mysqli instance :
$this->conn = new mysqli($servername,$user,$pass, $this->db);
but $this->db is null and has no value. you should change it to :
$this->conn = new mysqli($servername,$user,$pass,$db);
and another thing:
function __destruct() {
$this->close();
}
this function runs when php wants to destroy your object, But you have closed your connection already!
$con = #new DataBase();
$r = $con->sendQuery("show tables");
$con->close();

Fatal error: Call to a member function getOne() on a non-object [duplicate]

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm new to php oop.here i wanted to do database connectivity with singleton class but i got error like this:
Fatal error: Call to a member function getOne() on a non-object in C:\xampp\htdocs\singleton\new\singleton_db.php
here i have given two file
1.singleton_db.php
<?php
class database
{
public $query;
public $results;
public $conn;
public static $database;
//connect to the database
public function __construct()
{
$this->conn = mysql_connect('localhost','root','');
if ($this->conn)
{
mysql_select_db('test1');
}
}
public static function instance()
{
if (!isset(self::$database)) {
self::$database = new database();
}
return self::$database;
}
function getOne($sql) {
$result = $this->conn->getOne($sql); //Error in this line
if(database::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
return $result;
}
function startTransaction() {
//autoCommit returns true/false if the command succeeds
return $this->conn->autoCommit(false);
}
function commit() {
$result = $this->conn->commit();
if(database::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
$this->conn->autoCommit(true);
return true;
}
function abort() {
$result = $this->conn->rollback();
if(database::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
return true;
}
//returns numerically indexed 1D array of values from the first column
public function insert($table, $arFieldValues) {
$fields = array_keys($arFieldValues);
$values = array_values($arFieldValues);
// Create a useful array of values
// that will be imploded to be the
// VALUES clause of the insert statement.
// Run the mysql_real_escape_string function on those
// values that are something other than numeric.
$escVals = array();
foreach($values as $val) {
if(! is_numeric($val)) {
//make sure the values are properly escaped
$val = "'" . mysql_real_escape_string($val) . "'";
}
$escVals[] = $val;
}
//generate the SQL statement
$sql = " INSERT INTO $table (";
$sql .= join(', ', $fields);
$sql .= ') VALUES(';
$sql .= join(', ', $escVals);
$sql .= ')';
$hRes = mysql_query($sql);
if(! is_resource($hRes)) {
$err = mysql_error($this->conn) . "\n" . $sql;
throw new Exception($err);
}
return mysql_affected_rows($hRes);
}
}
2.data.php
<?php
require_once('singleton_db.php');
try {
$db = database::instance();
} catch (Exception $e) {
// No point continuing...
die("Unable to connect to the database.");
}
$sql = "SELECT count(1) FROM mytable";
$count = $db->getOne($sql);
print "There are $count records in mytable!<br>\n";
// start a transaction
$db->startTransaction();
// do an insert and an update
try {
$arValues = array();
$arValues['id'] = '#id#';
$arValues['myval'] = 'blah blah blah';
$newID = $db->insert('mytable', $arValues);
print "The new record has the ID $newID<br>\n";
// update the record we just created
$arUpdate = array();
$arUpdate['myval'] = 'foobar baz!';
$affected = $db->update('mytable', $arUpdate, "id = $newID");
print "Updated $affected records<br>\n";
// write the changes to the database
$db->commit();
} catch (Exception $e) {
// some sort of error happened - abort the transaction
// and print the error message
$db->abort();
print "An error occurred.<br>\n" . $e->getMessage();
}
?>
What could I do to fix this ?
Your problem is you haven't defined the
getOne();
method properly. The property
$this->conn
Is just the result of mysql_connect() function which is a "MySQL link identifier on success, or FALSE on failure". It is not an object, and such, you can not ask it for the getOne(); method.

Categories