MySQLi prepared query failing after first query - php

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?

Related

How can i get all the values in the query?

<?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
}

PHP MySQLI prepared statement breaks at get_results()

I am very new at mysqli prepared statements, in fact this is my first try at it. I have this block of code and I put echos inbetween each command, and it displays aaa and bbb but not ccc, what am i doing wrong here?
no errors come up, just a blank screen:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT title FROM `in-the-press`")) {
$stmt->execute();
echo 'aaa';
$stmt->bind_result($title);
echo 'bbb';
$result = $stmt->get_result();
echo 'ccc';
while ($stmt->fetch()) {
printf("%s %s\n", $title);
}
echo 'ddd';
$stmt->close();
}
$mysqli->close();
?>
UPDATE I was able to get this working, by doing the following:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT id, community, map, image FROM `googleMaps`")) {
$stmt->execute();
$stmt->bind_result($id, $community, $map, $image);
$stmt->fetch();
printf($id . ' ' . $community . ' ' . $map . ' ' . $image);
$stmt->close();
}
?>
but this only gives me 1 row of data, how do I get all rows of data?
To use get_result() you must use the mysqlnd driver. This is enabled by default in PHP 5.4 and later. If you're using an earlier version of PHP, you have to do some installation to get mysqlnd to work. See http://php.net/manual/en/mysqlnd.install.php
If you use get_result(), then you don't need to bind anything. You just fetch each row as an array, and reference the columns as elements of that array:
if ($stmt = $mysqli->prepare("SELECT title, community, map, image FROM `googleMaps `")) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
printf("%s %s\n", $row["title"], $row["community"]);
}
$stmt->close();
}
If you don't use get_result(), you use Mysqli in the old manner, binding variables to columns, and calling fetch() to populate the variables. But you need to run a loop until fetch() returns NULL when the result is finished.
if ($stmt = $mysqli->prepare("SELECT title, community, map, image FROM `googleMaps`")) {
$stmt->execute();
$stmt->bind_result($title, $community, $map, $image);
while ($stmt->fetch()) {
printf("%s %s\n", $title, $community);
}
$stmt->close();
}
You need to print your results in a loop, for instance you need to echo for each result found.
http://php.net/manual/en/control-structures.for.php

Binding results in MySQLi

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);

Using MYSQLI in seperate / distinct PHP functions

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();
?>

Mysqli query return empty results

im trying to get some data from my DB using this code:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli2 = new mysqli(********************);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql2 = "SELECT message FROM wall_workouts_names WHERE id = ? ";
$stmt2 = $mysqli2->prepare($sql2) or trigger_error($mysqli2->error."[$sql2]");
$id_for_wall = '43';
$stmt2->bind_param('s', $id_for_wall);
$stmt2->execute();
$stmt2->bind_result($message);
$stmt2->store_result();
$stmt2->fetch();
echo $message;
?>
My problem is that i get empty string in my echo.
But if i run the same query in my phpmyadmin i get good results.
Thanks for helping
Most likely there are no row to match condition in your WHERE clause, namely with id = 43
Check your incoming results like this.
while ($stmt->fetch()) {
echo $message;
}

Categories