PHP - prepared statements and json_encode - php

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

Related

Joining a string and array elements not working

Here is my PHP code:
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$statecodes = array(0=>"test1","test2");
while($i<sizeof($statecodes)) {
$ini = "users_";
$var = sprintf("%s%s", $ini, $statecodes[$i]);
print $var;
$query = "CREATE DATABASE IF NOT EXISTS" . $var;
$stmt = $mysqli->prepare($query);
/* Execute the statement */
$stmt->execute();
$i=$i+1;
/* close statement */
$stmt->close();
}
And the output i get is
users_
I want to create databases named user_test1 and user_test2
Try this out. You were missing a space after IF NOT EXISTS and your loop was broken due to not initializing your counter. PHP provides a lot of convenient methods for doing things like array traversal and string concatenation; looking at your code I'd guess your experience is with a much lower level language? Things like printf() come in handy for some tasks, but it's overkill when you just want to jam two strings together!
Finally, no need to prepare and execute a query if it isn't a prepared statement with placeholders. You will, however, want to sanitize your input and check the result of your query for errors.
<?php
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$statecodes = array("test1","test2");
foreach ($statecodes as $state) {
$var = "users_$state";
// remove dangerous characters!
$var = preg_replace("/[^\w]/", "", $var);
$query = "CREATE DATABASE IF NOT EXISTS $var";
$result = $conn->query($query);
if (!$result) {
//do something!
}
}

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

Trying to use Object Oriented code to display database information

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

Need Help With mysqli PHP select Statement

I have a couple of questions here, so any help will be greatly appreciated. I have three pages here.
//Page 1 - Constants
$dbhost = "database.url.com"; //Just made up
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "123456";
//Page 2 - The Function
//This is where i need to write the function select information from the database.
include ("include/page1.php");
$DBH = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
function selectInfo(){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
}
//This function obviously is not complete because I keep recieving different error messages. I guess i cannot figure out how to write a prepared select statement. Need some help here.
//Page 3 - Where the function is called and where the user would be
include ("include/page2.php");
//need to be able to call the function here with variables set.
$start = 0;
$end = 5;
selectInfo();
echo the data that i need in the database.
This probably looks like a complete mess, but hopefully you can get the idea i am trying to do here. I would like to be able to fetch the data so that i can display it something like
echo $stmt->title;
echo $stmt->id;
if that is possible. Can anyone please help me?
You need to execute the bind_param and execute method on your mysqli object:
$DBH->bind_param("ii", $start, $end);
And then execute the statement:
$DBH->execute();
Just have a close look at the mysqli API.
From php.net first example.
<?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 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();
?>
#mcbeav
You should change your function:
function selectInfo(){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
}
To something like this:
function selectInfo($limit, $offset){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
// Other stuff to get your values from this query
...
// Return the object with the results
return $values;
}
Everything you need is explained in the mysqli_prepare documentation.

Example php code for connecting and getting a sql stored proceedure

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

Categories