I'm transitioning from MYSQL to MYSQLI and I am in need of assistance with putting MYSQLI into separate / distinct functions.
From all the "tutorials" i have located on the web, they all have everyrything in one big long code, and not distinct / separate functions that my main scripts can call.
Eg :-
Connect to MYSQLI
Do SELECT
Exit MYSQLI
what i'm after is :-
MYSQLI.PHP
<?
function connect_mysqli()
{
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno();
}
// Return the connection back to where i called it ??
}
function do_query ($sql)
{
$row = $con->query("$sql")->fetch_array();
return $row;
}
function close_mysqli()
{
$mysqli->close();
}
?>
in my script i want to call :-
another.php
<?
include_once("MYSQLI.PHP");
connect_mysqli();
....
do some SELECT
do some UPDATE
close_mysqli();
?>
So far, from the error codes I am receiving, the "connection" to mysqli is not being passed to/from my other script(s)
Has anyone got a working / tested example of mysqli using functions (not just half the code) - but a working example of simple SELECT
Once i get that far, i can do the rest.
fix your include file to
/**
* #return mysqli
*/
function connect_mysqli()
{
$con = mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno());
}
return $con;
}
function do_query ($con, $sql)
{
$row = $con->query("$sql");
if($row) {
return $row->fetch_array();
}
return null;
}
function close_mysqli($con)
{
$con->close();
}
now you can run a script like this
include_once("MYSQLI.PHP");
$connection = connect_mysqli();
if(null !== $connection) {
print_r(do_query($connection, "SELECT * FROM yourTable"));
close_mysqli($connection);
}
but for correct handling create a connection interface and a implementation for mysqli like this
interface myConnectionClass {
function connect();
....
}
and a mysqli implementation
class myMysqlIConnection implements myConnectionClass {
function connect() {
//do more... save connection etc...
return true; //sucess
}
}
Example Demos
Scroll down there are a lot of exmaples...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET #a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>
Related
I have code, which is basically a copy of a php.net's code, but for some reason it does not work. Here is the code on php.net:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The first change I made was the connection:
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
The second change I made was the queries:
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
EDIT: The full code with my changes
<?php
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The error I get:
Strict standards: mysqli::next_result(): There is no next result set.
Please, call mysqli_more_results()/mysqli::more_results() to check
whether to call this function/method in
address on line line number
I searched a solution over the net, and particularly here on StackOverflow, but I did not find helpful solutions. Most of the solutions I found were one of those two:
In this solution,#Hammerite says to change the loop from do-while to while. This suggest that php.net's code has a problem in its logic, and I find it very hard to believe. But more importantly, it just does not work for me.
In this solution, #mickmackusa suggests to add a condition in the while and change $mysqli->next_result() to $mysqli->next_result() && $mysqli->more_results(), but this solution do not work quite well. It does indeed removes the error but it omits the last result.
Try it with
} while ($mysqli->more_results() && $mysqli->next_result());
sscce:
<?php
ini_set('display_errors', 'on');
error_reporting(E_ALL|E_STRICT);
$mysqli = new mysqli("localhost", "localonly", "localonly", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query('CREATE TEMPORARY TABLE City (ID int auto_increment, `Name` varchar(32), primary key(ID))') or die($mysqli->error);
$stmt = $mysqli->prepare("INSERT INTO City (`Name`) VALUES (?)") or die($mysqli->error);
$stmt->bind_param('s', $city) or die($stmt->error);
foreach(range('A','Z') as $c) {
$city = 'city'.$c;
$stmt->execute() or die($stmt->error);
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (!$mysqli->multi_query($query)) {
trigger_error('multi_query failed: '.$mysqli->error, E_USER_ERROR);
}
else {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("'%s'\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
prints
'localonly#localhost'
-----------------
'cityU'
'cityV'
'cityW'
'cityX'
'cityY'
without warnings/notices.
In my db I have some stored procedures.
I want to call the one of them, and according to the results I get from this procedure, i will determine weather to call the second one or not.
As you can see in the isUserValid() method I've used $result->free_results()
but still when calling the other procedure I get: Commands out of sync; you can't run this command now
This is my calling to the db functions:
/**
* Run a new query on the db.
* this will open an close the connection to the db
* #param $query string the query to run
* #param $verifyAccessToken boolean true if user validation is needed before query is executed, false otherwise
* #return bool|mysqli_result the result of the query if any or true or false in a non query
* #throws Exception on connection and query errors
*/
private function queryDb($query,$verifyAccessToken)
{
// if ($this->test)
// echo $query . "<br>";
//create a new mysqli connection
$mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
//set the charset for the connection
if (!$mysqli->set_charset("utf8"))
{
$mysqli->close();
throw new Exception ("Error setting UTF 8 DB connection");
}
//check if the connection was ok
if (mysqli_connect_errno())
{
$mysqli->close();
throw new Exception("Error connecting DB");
}
//if verification is needed - verify access token
if ($verifyAccessToken && !$this->isUserValid($mysqli))
{
$mysqli->close();
throw new Exception(ACCESS_TOKEN_INCORRECT);
}
//get results
$result = $mysqli->query($query);
//check if there were now error in query. if so - throw an exception
if (!$result)
{
$mysqlError = $mysqli->error . __LINE__;
//close the connection
$mysqli->close();
throw new Exception ("mySQL Error: " . $mysqlError);
}
//fetch the results into an array
$rows = $result->fetch_all(MYSQLI_BOTH);
//close the connection
$result->close();
$result->free();
$mysqli->close();
//return the results if any
return $rows;
}
/**
* Check if user is valid
* #param $mysqli mysqli connection to db
* #return true if user is valid, false otherwise
*/
function isUserValid($mysqli)
{
//Check if there is a saved access token. if not - throw an exception
if (is_null($this->user) || $this->user->getPicoAccessToken() == null)
throw new Exception(ACCESS_TOKEN_INCORRECT);
//get user details
$facebookId = $this->user->getFacebookId();
$picoAccessToken = $this->user->getPicoAccessToken();
//create verification query
$verificationQuery = "Call isUserValid('$facebookId','$picoAccessToken')";
//execute query
$result = $mysqli->query($verificationQuery);
//if query had error - throw exception
if (!$result)
{
$mysqlError = $mysqli->error . __LINE__;
//close the connection
$mysqli->close();
throw new Exception ("mySQL Error: " . $mysqlError);
}
$rows = $result->fetch_all(MYSQLI_ASSOC);
$rows = $rows[0];
$result->free_result();
//return user valid status
return isset($rows["isUserValid"]) && $rows["isUserValid"] == 1;
}
Every stored procedure returns at least two results
one (or many) actual results
one empty result to tell the client there are no more results.
You have to use mysqli_more_results()/mysqli_next_result() to clean them.
If your procedure returns only one result, or you just don't want any extra results but the first one, you can clean up the results queue with this code snippet:
while($mysqli->more_results())
{
$mysqli->next_result();
if($res = $mysqli->store_result())
{
$res->free();
}
}
The currently accepted answer wont work as-is, i think next_result() should not be called before the first result.
This is an example that does work:
if (!$mysqli->multi_query("CALL p()")) {
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
printf("---\n");
var_dump($res->fetch_all());
$res->free();
} else {
if ($mysqli->errno) {
echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
} while ($mysqli->more_results() && $mysqli->next_result());
From the PHP manual http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
re connect database $this->db->reconnect(); // likes in codeigniter
i want to execute a more then 3 queries in a single statement.
is is possible?
i need to insert the values into the table
select entire table
count the users.
is it possible to do all these in a single statement.
Thanks
You can use more than 3 queries only in mysqli using mysqli_multi_query(), but mysql doesn't support it.
Example code :
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Change it accordingly. It shows multiquery in action using mysqli.
I am trying to use Object Oriented code to display users (management) in a database, The variables are loaded with the right info for connection, My DB code is
/* Code to Connect to the Database */
$mysqli = new mysqli($host, $username, $password);
if($mysqli->connect_errno){
echo "Failed to connect to the Database: " . $mysql->connect_error;
}
and the code i'm using to display the users is
$query = ("SELECT m_username, m_email, m_fname, m_sname, m_mccode, m_mobile FROM management");
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ($row["m_username"], $row["m_email"], $row["m_fname"], $row["m_sname"], $row["m_mccode"], $row["m_mobile"]);
}
/* Frees the result set */
$result->close();
/* Close the Connection */
$mysqli->close();
}
When I go to the page that has this code, I get nothing displayed and there is users in the DB.
You haven't provided database name, so database not selected. Change mysqli_connect() arguments:
$db = 'mydbname';
$mysqli = new mysqli($host, $username, $password, $db);
Also, you may try to add MySQL debug messages, while testing your scripts:
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ($row["m_username"], $row["m_email"], $row["m_fname"], $row["m_sname"], $row["m_mccode"], $row["m_mobile"]);
}
/* Frees the result set */
$result->close();
} else {
/* Show error message */
echo $mysqli->error;
}
/* Close the Connection */
$mysqli->close();
Can any one give
The Example php code for connecting and getting a sql stored proceedure
what do you prefer to use? Here is an example taken from php.net:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CALL get_items(1, #param1, #param2); ";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
remember, that you have to free the resultset, if you do not, you will get an error while executing a next query.
Before I know something about mysqli, I apply mysqli to handle sp's. Just take a look at the follwing example:
$rs = mysql_query("CALL get_items(1, #param1, #param2); ");
$rs = mysql_query("SELECT #param1, #param2" );
while($row = mysql_fetch_assoc($rs))
{
print_r($row);
}
Calling a Stored procedure with PDO