In the code below if I try to fetch results after two successive executions with different sets of parameters, it shows the same result set(the first one twice), instead of showing both the results with different parameters. What should I do? Also, in the PHP manual $sqli->bind_results() is put after $sqli->execute(), is it always mandatory or is it valid also to put $sqli->bind_results() before $sqli->execute() ?
<?php
$mysqli = new mysqli("localhost","root","","test");
/*check connection*/
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
/*create prapared statement*/
$sqli = $mysqli->prepare("select post_id from posts where id=?");
/*bind params*/
$sqli->bind_param('i',$id);
/*set params*/
$id =1;
/*execute prapared statement*/
$sqli->execute();
/*bind results*/
$sqli->bind_result($post_id);
while($sqli->fetch())
{
echo ' '.$post_id;
}
echo '<br/>fetch new record<br/>';
/*set params*/
$id =2;
/*execute prapared statement*/
$sqli->execute();
while($sqli->fetch())
{
echo ' '.$post_id;
}
Executing in loops:*
Scene1: calling bind_result($post_id) repeatedly
<?php
$mysqli = new mysqli("localhost","root","","test");
/*check connection*/
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
/*create prapared statement*/
$sqli = $mysqli->prepare("select post_id from posts where id=?");
/*bind params*/
$sqli->bind_param('i',$id);
for($x=0;$x<1000;$x++)
{
$id =$x;
$sqli->execute();
/*****bind results*****/
$sqli->bind_result($post_id);
while($sqli->fetch())
{
echo ' '.$post_id;
}
}
?>
Scene2: calling bind_result($post_id) once
<?php
$mysqli = new mysqli("localhost","root","","test");
/*check connection*/
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
/*create prapared statement*/
$sqli = $mysqli->prepare("select post_id from posts where id=?");
/*bind params*/
$sqli->bind_param('i',$id);
/*****bind results*****/
$sqli->bind_result($post_id);
for($x=0;$x<1000;$x++)
{
$id =$x;
$sqli->execute();
while($sqli->fetch())
{
echo ' '.$post_id;
}
}
?>
Now,as par PHP manual bind_result() should be used after execute(),but as shown in the scene1 above this will call "bind_result()" repeatedly whereas in scene2 it is called just once and still it is doing well. Which approach is better? Is scen2 valid?
Yes, you need to run bind_result after each execute.
From the manual...
Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch().
So, you're only missing the second (required) call to bind_result...
$id = 2;
$sqli->execute();
$sqli->bind_result($post_id);
Related
<?php
$mysqli = new mysqli("localhost", "root", "", "titan3d");
if (mysqli_connect_error()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sdate = "";
$stime = "";
if(isset($_POST['sdate']))
{
$sdate = $_POST["sdate"];
}
if(isset($_POST['stime']))
{
$stime = $_POST["stime"];
}
$statement = $mysqli->prepare("SELECT bookedseat FROM bookings WHERE sdate = ? AND stime = ?");{
$statement->bind_param("si", $sdate, $stime);
if (!$statement->execute()) {
trigger_error('Error executing MySQL query: ' . $statement->error);
}
$statement->bind_result($book);
$statement->fetch();
printf($book);
//header('Location: http://localhost/My%20Project/seats.html');
$statement->close();
}
$mysqli->close();
?>
This is my php file made to get the data from a form and make a query and then display the results.
When executed,the php works perfectly.
But it only displays the first value in the query.
Why is it?
How can I display all the values in my query?
You need to use $stmt->fetch() in a while loop, you can then iterate over each the returned row.
while ($stmt->fetch()) {
// $book will have the value of bookedseat for the current row
}
I'm converting to Mysqli object-oriented (or trying to). I have various category pages. I'd like to use a parameter placeholder '?' in the include and then call up the right category on the category page.
This is as far as I've gotten. How do I indicate the category on my page? All works fine if I indicate WHERE category = apples.
I have this include at top of a category page
<?php require_once 'maincats_mysqli.php' ?>
which is below:
<?php
$db = new mysqli('host', 'userName', '', 'dbName');
if ($db->connect_error) {
$error = $db->connect_error;
} else {
$sql = "SELECT pageName, gImage, prodName, prodPrice
FROM tableName
WHERE category = '?'
ORDER BY dtList DESC";
$stmt->bind_param('s', ['$category']);
$result = $db->query($sql);
if ($db->error) {
$error = $db->error;
}
}
function getItem($result) {
return $result->fetch_assoc();
}
?>
Below is part of one category page. How do I indicate which category? Any help would be appreciated.
<?php
if (isset($error)) {
echo "<p>$error</p>";
}
?>
<?php
while ($item = getItem($result)) {
?>
<a href="http://www.example.com/<?php echo $item['pageName']; ?>">
<img src="http://www.example.com/<?php echo $item['gImage']; ?>"</a>
<a href="http://www.example.com/<?php echo $item['pageName']; ?>">
<?php echo $item['prodName']; ?></a>
<?php echo $item['prodPrice']; ?>
<?php
}
?>
First, you don't declare $stmt.
Second, ? is not a wildcard in this case, it's a parameter placeholder. You can use such placeholders when preparing the query, with $mysqli->prepare($sql). See documentation: http://php.net/manual/en/mysqli-stmt.bind-param.php
$sql = "SELECT pageName, gImage, prodName, prodPrice
FROM tableName
WHERE category = ?
ORDER BY dtList DESC";
$stmt = $db->prepare($sql);
Third, you encapsulate your variable in single quotes, so it's a string with a dollar and the name of your variable, not its content. And it must not be in an array:
$stmt->bind_param('s', $category);
Last: where does $category comes from? It's not defined in the script you show us. I guess it's from $_GET, so the previous line should be:
$stmt->bind_param('s', $_GET['category']);
Finally, you need to execute your statement, which contains the query:
$stmt->execute();
EDIT:
To fetch results, you don't need that getItem() function. Just remove it.
$result = $stmt->get_result();
Then you can loop over $result and fetch each row:
while ($item = $result->fetch_assoc()):
// do you stuff
endwhile;
Note that I use here the PHP control structure alternative syntax which is more clear in your case (endwhile is more explicit than just })
You're missing the prepare(). Look at the first example in the PHP manual page:
<?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();
}
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Note that you must not quote binded parameters.
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.
I have two prepared statements (for example) where the second statement is to be executed within the while(stmt1->fetch()){} loop. But, the inner statement (stmt2) doesn't execute within the first while loop:
<?php
$mysqli = new mysqli("localhost","root","","test");
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
$stmt1 = $mysqli->prepare("select id from posts");
$stmt2 = $mysqli->prepare("select username from members where id=?");
$stmt1->execute();
$stmt1->bind_result($ID);
while($stmt1->fetch())
{
echo $ID.' ';
/*Inner query*/
$stmt2->bind_param('i',$id);
$id =$ID;
$stmt2->execute();
$stmt2->bind_result($username);
while($stmt2->fetch())
{
echo 'Username: '.$username;
}
/*Inner query ends*/
}
?>
If I cut-paste the inner query part outside the outer while loop, it executes,but it is useless. What should I do to execute it properly?
Why do nested loop on it, when you can do INNER JOIN instead.
<?php
$mysqli = new mysqli("localhost","root","","test");
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
if($stmt1 = $mysqli->prepare("SELECT posts.id,members.username FROM posts INNER JOIN members ON posts.id=members.id")){
$stmt1->execute();
$stmt1->bind_result($id,$username);
while($stmt1->fetch()){
printf("ID # %d.<br>Username: %s<br><br>",$id,$username);
}
$stmt1->close();
}
$mysqli->close();
?>
I have one function selecting a load of information from one table. This then launches another function to get some info from another table.
Here's the shortened code:
$con = new mysqli("localhost", "user", "password");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$con->select_db("stories_test");
getStories($con);
function getStories($con) {
... //get's a load of data from one table
$result = getStoryName($con, $stringstoryid);
... //More stuff here
}
function getStoryName($con) {
$newquery = "SELECT storyname, genre FROM stories WHERE storyid = 'Anewstory9856'";
if ($stmt = $con->prepare($newquery)) {
echo $newquery;
$stmt->execute();
$stmt->bind_result($storname, $genre);
while ($stmt->fetch()) {
$resultarray = array (
'storname' => $storname,
'genre' => $genre
);
}
}
else {
echo 'statement failed';
}
return $resultarray;
}
All I ever get is 'statement failed' from the second query.
I have tried the exact same query in a separate script on its own and it works fine, but here it seems to fail at 'prepare'.
Does anyone have any clues?