PHP MySQLI prepared statement breaks at get_results() - php

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

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 Object-Oriented with Wildcard

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.

mysqli fetch result as assoc array

$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 Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
can somebody help me to this statement/syntax? i want the result as associative array (indexed by fieldname) and don't want to write this "$stmt->bind_result($name, $code);" statement. thanks
As you are not actually using any parameters i.e. ? then you dont really need to do a ->prepare
So you could just use the ->query() and ->fetch_assoc() mechanism
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
$result = $mysqli->query($query)
if ( $result === FALSE ) {
echo $mysqli->error;
exit;
}
/* fetch values */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row['name'], $row['code']);
}
After your comment
This is another option, if you have to keep the prepare
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
// there seems to be some confusion in the manual as to
// whether this next statement is needed or not
// see if that helps
$stmt = $mysqli->stmt_init();
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
if (!$stmt->execute()) {
echo $stmt->error;
exit;
}
$result = $stmt->get_result();
/* fetch values */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row['name'], $row['code']);
}
} else {
echo 'Failed to prepare statement';
exit;
}
The call to $stmt->get_result() basically converts a mysql_stmt object to a mysql_result object
Try this.
$stmt = $mySqli->query($query);
$countries = mysqli_fetch_all($stmt, MYSQLI_ASSOC);
$stmt->close();
Just try this :
while ($stmt->fetch(PDO::FETCH_ASSOC)) {
printf ("%s (%s)\n", $name, $code);
}

PHP - prepared statements and json_encode

I want to create a php script using prepared statements to query a table in my database and return the results in json format. I have a table of doctors and i want to return the doctors of a given speciality. I have a version of the script that doesn't use prepared statements that works fine. But when i use prepared statements my script doesn't work.
Non - prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality='$speciality'";
$result = $mysqli->query($query) or die("Error executing the query");
while($row = $result->fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$mysqli->close();
?>
prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality=?";
if ($stmt = $mysqli -> prepare($query)){
$stmt -> bind_param("s", $speciality);
$stmt -> execute();
$result = $stmt -> get_result();
while($row = $result -> fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$stmt -> close();
} else {
echo $mysqli->error;
echo "no entry found";
}
$mysqli->close();
?>
What am i doing wrong? I don't get a mysqli error which means that the problem is after the execution of the query but i just don't know what it is.
Edit: What i mean by saying it doens't work is that i don't get anything back. The html body of the page after the execution is completely empty. On the other hand if i use the other script i posted (without prepared statements) i get the expected result.
UPDATED:
Use this:
/* bind result variables */
$stmt->bind_result($col1,$col2,$col3,$col4);
/* fetch values */
while ($stmt->fetch()) {
$output[]=array($col1,$col2,$col3,$col4);
}
Instead. Hope it helps.
anyone please give reason of putting downvote.
ini_set('display_errors',1);
error_reporting(E_ALL);
and then look at HTML body again. Most likely get_result is not supported but I hate to guess.
Make sure your version of PHP is compatible with the method
http://php.net/manual/pt_BR/mysqli-stmt.get-result.php
To get data as associative array you can do as follow:
$stmt->bind_result($col1, $col2);
$rows = [];
while ($stmt->fetch()) {
$rows[]=array("col1"=>$col1, "col2"=>$col2);
}

MySQLi prepared query failing after first query

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?

Categories