I am having difficulty calling and displaying the content when I call a procedure more than once in a page. I am trying to display two separate record sets from two different SP calls for MYSQL. I can display the first call but the second fails. I'm not sure what I am doing wrong but perhaps someone can kind help?
I keep getting the error when I call the second procedure:
Error calling SPCommands out of sync; you can't run this command now
I'm running on windows
Code below... PHP
// First call to SP
$page = 2;
$section = 1;
include("DatabaseConnection.php"); //general connection - works fine
$sql = 'CALL GetPageContent("'.$page.'", "'.$section.'")';
$result = mysqli_query($conn, $sql) or die('Error calling SP' .mysqli_error($conn));
while($row=mysqli_fetch_assoc($result))
{
// DO STUFF< REMOVED TO MAKE READING CLEARER
}
mysqli_free_result($result);
//SECOND CALL BELOW
$section = 2; // change parameter for different results
$sql = 'CALL GetPageContent("'.$page.'", "'.$section.'")';
$result = mysqli_query($conn, $sql) or die('Error calling SP' .mysqli_error($conn));
while($row=mysql_fetch_assoc($result))
{
// DO STUFF< REMOVED TO MAKE READING CLEARER
}
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:
<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// 1st Query
$result = $db->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
// 2nd Query
$result = $db->query("call getGroups()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$group_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
else echo($db->error);
// Close connection
$db->close();
?>
if you are calling more than one procedure on a single script page, you should call mysqli_next_result($connection_link) before calling another procedure.
consider below sample code block:
<?php
$data = new \stdClass();
require('./controller/dbController.php');
$query = 'CALL getActiveProductCount()';
$result = mysqli_query($con, $query);
$result = mysqli_fetch_assoc($result);
$data->active_product = $result['count'];
mysqli_next_result($con); // required to perform before calling the procedure again
$query = 'CALL getPurchasedProductCount()';
$result = mysqli_query($con, $query);
$result = mysqli_fetch_assoc($result);
$data->purchased = $result['count'];
mysqli_next_result($con);
Related
I need to write a PHP function to echo out MySQL rows as I give it the SQL query I want to be executed as the function argument. I have tried out the following code but it is giving me an undefined index error
function runQuery($query) {
$conn = mysqli_connect('localhost', 'root', '', 'mydb');
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
the code I am using to call the function is;
runQuery(SELECT * FROM mytable WHERE id='5')
echo $resultset['name'];
this, however, gives me this error, undefined index 'resultset' on line 25. any kind assistance would be appreciated
You dont have a $resultset in the scope of where you call the function. The function creates one, but that is only visible inside the function.
You will also have to put QUOTES around the query, you are passing a string there so it needs to be quoted.
Your errors should have generated quite a few error messages, if you were not getting them I have added 4 lines of code you should add while testing code for example if you are testing on a LIVE server with error reporting turned off.
You should also change the function to ensure you always return something
So amend the call to
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
function runQuery($conn, $query) {
$resultset = [];
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
$resultset = runQuery($conn, "SELECT * FROM mytable WHERE id='5'");
// as result will now be a multidimentional array
// you will need to loop over that to get each returned row
foreach ( $resultset as $row ) {
echo $row['name'];
}
AFTER your edit there is another error
$conn is not created inside the function, so will be invisible in the function code unless passed as a parameter to the function (there is another way but lets not get into the bad habit of using global variables)
First, your code is probably vulnerable to SQL Injection. Please take care of that, by using prepared statements for instance.
https://www.w3schools.com/sql/sql_injection.asp
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
Other than that, you do not assign the return value of your function to a variable. You cannot use the $resultset defined in the function scope outside the function, as it is a different scope. Try the following:
$resultset = runQuery("SELECT * FROM mytable WHERE id='5'")
echo $resultset['name'];
I built a similar function recently - here is my code
function returnSQL($conn, $nameSql) {
$result = mysqli_query($conn, $nameSql);
if (!$result) {
return 0;
}
while ($res = mysqli_fetch_assoc($result)) {
$data[] = $res;
}
return $data;
}
The connection is setup outside the function and passed in as an argument along with the sql like this...
$conn = mysqli_connect($servername, $username, $password, $DBName);
if (!$conn) {
echo 'Failed to connect to database :- ' . $DBName . '<br>';
die();
}
$sql = "SELECT * FROM table";
$data = returnSQL($conn, $sql);
I'm no expert, but this works for me :)
What I notice from your code is that you are trying to access $resultset outside of the function it is declared in and I think it is not available as a global variable - perhaps it should be something like:
$returnValue = runQuery(SQL statement);
// $returnValue is assigned the array returned from runQuery()
echo $returnValue['name'];
I have an old PHP code that has mysql in it.
It gets an array from a SELECT statement, adds it to a JSON object, as a property and echoes the encoded JSON.
I changed it around to use mysqli, but when I try to get the rows, and create an array out of them, it just returns nothing.
Here's the old mysql code:
$con = mysql_connect('host','account','password');
if (!$con)
{
//log my error
};
mysql_select_db("database_name", $con);
mysql_set_charset('utf8');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$query = mysql_query($sql);
$results = array();
while($row = mysql_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Version1: Here's the new one that I tried writing:
$con = mysqli_connect('host','account','password','database_name');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$results = array();
if($result=mysqli_query($con, $sql))
{
while ($row=mysqli_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
else
{
//error
}
Version2: Second thing I tried, which only returns 1 ROW:
...same as above until $sql
if($result=mysqli_query($con,$sql))
{
$row=mysqli_fetch_assoc($result);
return $row;
}
Version3: Or I tried to completely mirror the mysql structure like this:
$sql = "SELECT ...";
$query = mysqli_query($con, $sql);
$results = array();
while($row = mysqli_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Wrapping the resulting array into the JSON:
$obj = new stdClass();
$obj->Data = $results;
$obj->ErrorMessage = '';
die(json_encode($obj)); //or echo json_encode($obj);
None of the mysqli version are working, so I was thinking there might be an important change in the way these arrays are created.
Any tips on what could be wrong on the first mysqli example?
With Version2 I can tell that the SQL connection is there, and I can at least select a row. But it's obviously only one row, than it returns it. It makes me think, that building up the array is the source of the problem, or it's regarding the JSON object...
LATER EDIT:
OK! Found a working solution.
ALSO, I played around with the data, selected a smaller chunk, and it suddenly worked. Lesson from this: the function is not responding the same way for 40 rows or for 5 rows. Does it have something to do with a php.ini setting? Or could there be illegal characters in the selection? Could it be that the length of a 'Note' column (from the db) is too long for the array to handle?
Here's the working chunk of code, that selects some rows from the database, puts them into an array, and then puts that array into an object that is encoded into JSON at the end, with a statusmessage next to it. Could be improved, but this is just for demo.
$con = mysqli_connect('host','username','password','database_name');
if (!$con)
{
$errorMessage = 'SQL connection error: '.$con->connect_error;
//log or do whatever.
};
$sql = "SELECT Field1 as FieldA, field2 as FieldB, ... from Table where ID='something'";
$results = array();
if($result = mysqli_query($con, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
else
{
//log if it failed for some reason
die();
}
$obj->Data = $results;
$obj->Error = '';
die(json_encode($obj));
Question is: how can I overcome the issue regarding the size of the array / illegal characters (if that's the case)?
Your "Version 1" seems to be correct from a PHP perspective, but you need to actually handle the errors - both when connecting and when performing the query. Doing so would have told you that you don't actually query a table, you're missing FROM tablename in the query.
Use mysqli_connect_error() when connecting, and mysqli_error($con) when querying to get back the actual errors. General PHP error-reporting might also help you.
The code below assumes that $parameter is defined prior to this code.
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error());
$sql = "SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = '".$parameter."'";
$results = array();
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
return $results;
} else {
return mysqli_error($con);
}
Error-reporing
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
at the top of your file, directly after <?php would enable you to get the PHP errors.
NOTE: Errors should never be displayed in a live environment, as it might be exploited by others. While developing, it's handy and eases troubleshooting - but it should never be displayed otherwise.
Security
You should also note that this code is vulnerable to SQL-injection, and that you should use parameterized queries with placeholders to protect yourself against that. Your code would look like this with using prepared statements:
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error())
$results = array();
if ($stmt = mysqli_prepare("SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = ?")) {
if (mysqli_stmt_bind_param($stmt, "s", $parameter)) {
/* "s" indicates that the first placeholder and $parameter is a string */
/* If it's an integer, use "i" instead */
if (mysqli_stmt_execute($stmt)) {
if (mysqli_stmt_bind_result($stmt, $field1, $field2) {
while (mysqli_stmt_fetch($stmt)) {
/* Use $field1 and $field2 here */
}
/* Done getting the data, you can now return */
return true;
} else {
error_log("bind_result failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("execute failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("bind_param failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("prepare failed: ".mysqli_stmt_error($stmt));
return false;
}
References
http://php.net/mysqli.prepare
How can I prevent SQL injection in PHP?
I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);
I got a simple query looking like this:
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
Running this query gives me absolutely nothing. No errors but no result at the same time. I can't figure out whats wrong, help me please.
It looks like there may be a few things going on here:
According to the mysqli_connect_errno() Documentation, you should be checking for !$con rather than mysqli_connect_errno($con) in your if statement.
When a connection error is encountered, you're calling the error function but not printing it.
According to the mysqli_query() documentation, the first argument should be the database connection, the second being the query itself.
When a query errors out, you're calling mysql_error() when you should be calling mysqli_error(), passing it the connection. Again, according to documentation
Try this out and see if this resolves your problems:
<?php
$con = mysqli_connect("host","username","password","default_database");
if(!$con) {
print mysqli_connect_error();
} else {
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($con, $query) or die (mysqli_error($con));
while($row = mysqli_fetch_assoc($result)) {
echo $row['email'];
}
}
$result = mysqli_query($query) or die (mysql_error());
Needs a mysqli resource link and also its not mysql_error()
if ($result = mysqli_query($con,$query))
{
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
PHP is case-sensitive, so there is a very good change that your column in the database is actually named Email and then you have no result when you check $row['email'], because the E has to be upper case.
What you can do is make sure you use the right case in PHP, or select just the fields you want. MYSQL isn't case-senstive, so if you do the following it will work.
Also a good way to check if you have the right case: use var_dump($row) (I've added it to the code just to show you)
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT email FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
var_dump($row);
}
}
I am learning mysqli.
I am trying to fetch data from a table "tbllogin".
//DATABASE CONNECTION
$hostname="p:localhost";
$database="dbLogin";
$username="user1";
$password="pwd1";
$mysqli = new mysqli($hostname, $username, $password,$database);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// Create Query
$query = "SELECT * FROM tbllogin";
// Escape Query
$query = $mysqli->real_escape_string($query);
echo $query;
// Execute Query
if($result = $mysqli->query($query)){
print_r($result);
while($row = $mysqli->fetch_object($result)){
echo $row->column;
}
//Free result set
$result->close();
}
?>
But $mysqli->fetch_object($result) is not working. The if statement containing $mysqli->fetch_object($result) does not execute. I cannot identify if there is any error.
Please help.
Also, suggest whether mysqli procedural form is better or object-oriented form?
Thanks in advance.
Shouldn't that be $result->fetch_object() ?
http://php.net/manual/en/mysqli-result.fetch-object.php
From Example 1:
if ($result = $mysqli->query($query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
According to the answers on this stackoverflow page, there is not much of a difference between the two.
Try this:
if($result = $mysqli->query($query)){
print_r($result);
while($row = $result->fetch_object($result)){
//do something
}
}
You need to chain the commands together.