binding parameters in MySQl and PHP - php

I am trying to learn how to use prepared statements in my PHP, to get data out from MySQL database. At the moment I am not getting anything printed out.
I need to have a while loop there is going through my rows in the database. Is that correct?
Am I on the correct way here, or what am I missing? I made some comments in the code, to describe what I am doing.
<?php
$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");
// Execute prepared statement
if ($stmt->execute()) {
$success = true;
}
// Make variables ready
$head = null;
$desc = null;
$plac = null;
// Bind result to variables
$stmt->bind_result($head, $desc, $plac);
while ($stmt->fetch()) {
// What should go here?
echo "Headline: ".$head."Description: ".$desc."Place: ".$place;
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
if($success) {
echo "Selected Succesfull";
} else {
echo "Failed: " . $stmt->error;
}
}
?>

That code when executed it should give you an error :
Invalid parameter number: no parameters were bound
You need to bind your parameters as you are using placeholders
$stmt->bind_param("sss", $headline, $description, $place); //missing from your code
where "sss" is the dataType in this case a string and $headline, $description, $place are your variables that you replacing with placeholders
Your code should be
<?php
$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");
//bind parameters
$stmt->bind_param("sss", $headline, $description, $place);
if ($stmt->execute()) {
$stmt->bind_result($head, $desc, $plac);
while ($stmt->fetch()) {
echo "Headline: " . $head . "desc: " . $desc . "Place: " . $plac;
}
$stmt->close();
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
?>

Related

sql prepared statement not showing output

I am new to prepared statements. This function is not showing any output. What could the be problem?
function selectFwhere($id) {
$con = mysqli_connect('localhost','root','','car_rental');
$sql = mysqli_prepare($con,'SELECT * FROM `car_admin` WHERE admin_id = ?') or die("Unable to prepare statement: " . $con->error);
$sql->bind_param('i',$id);
$sql->execute();
$result = $sql->get_result();
while($row = $result->fetch_assoc() ){ echo " ".$row['admin_username']; }
$sql->close();
$con->close();
selectFwhere(1);
}
You need to move the line selectFwhere(1); outside the function body, after the closing }

How can I make a JSON from a MySQL prepared statement in PHP?

I have this code in PHP where I'm trying to make a JSON based on the result of a prepared statement. The problem is that it is returning a completely white page, nothing appears.
$con = mysqli_connect(HOST,USER,PASS,DB);
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
array_push($result,
array('Id'=>$tweetid,
'Body'=>$body,
));
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
I already made the content of $tweetid and $body be printed inside the while statement as test and it works fine, meaning that the problem is not the query, but something with the array. What am I missing?
Thanks!
Try like this
$result = array();
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
Demo :https://3v4l.org/XZOu5
I found the problem after some debugging. The problem was in the json_enconde function, which was silently failing because of JSON_ERROR_UTF8 type of error. I had some problems of special characters from my native language before I had success with just JSON_UNESCAPED_UNICODE before, but this time I added mysqli_set_charset($con, "utf8"); to the top of the code and it is now working. For the sake of completeness, the language is Brazilian Portuguese. The complete code is as follows.
$con = mysqli_connect(HOST,USER,PASS,DB);
mysqli_set_charset($con, "utf8");
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
Thanks for Barclick Flores Velasquez for the help. I'm new in php and I didn't know there was print_r for debugging, it helped a lot finding the solution.

Prepared statement does not print correct

I have made a prepared statement, but I keep getting printed my else statement, which in this case is 0 results. I do not get any errors in my code. Is there something I am missing here?
<?php
include 'dbconnection.php';
error_reporting(E_ALL); ini_set('display_errors', 1);
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
if(isset($_POST["headline"], $_POST["description"])) {
$head = trim($_POST["headline"]);
$desc = trim($_POST["description"]);
}
$query = ("SELECT headline, description FROM articles WHERE headline=? AND description=?");
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $head, $describe);
$stmt->execute();
$stmt->bind_result($head, $describe);
$stmt->store_result();
if ($stmt->num_rows > 0) {
while($stmt->fetch()){
echo"[ $head -> $describe ]<br />";
}
}
else
{ echo"[ 0 results ]"; }
$stmt->close();
?>

Can I get results from mysqli_stmt_bind_result without looping through it?

Using http://php.net/manual/en/mysqli-stmt.bind-result.php as a reference, I created:
$conn = new mysqli($host, $user, $password, $database) or die("Error " . mysqli_error($link));
$userID = json_decode(file_get_contents('php://input'), true)["userID"];
$sql = "SELECT name
FROM users
WHERE id = ?";
$stmt = mysqli_prepare($conn, $sql);
if ($stmt) {
mysqli_stmt_bind_param($stmt, "i", $userID);
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $name);
while (mysqli_stmt_fetch($stmt)) {
if ($name != "") {
echo '{"name": ' . $name . '}';
} else {
echo '{"name": "Anonymous" }';
}
}
}
}
}
The way this is now, it works in getting the user's name.
However, I'm reluctant to use a while loop when I know my query is only returning one row, so I looked for ways to get the value without using a loop but couldn't find any.
I tried removing the while loop just to see what would happen, and it failed to get the user's name. Is there a way I can get the result of my query using mysqli_stmt_bind_result without using a loop? If not, is there something else I can use to do what I want?
Yes, when you're only expecting one row, and know that it will only return that one, to be returned you don't need to loop over anything - it would be redundant.
You can remove the while-loop, but you'd still need the argument, mysqli_stmt_fetch($stmt) to actually fetch the results.
if ($stmt = mysqli_prepare($mysqli, $sql)) {
mysqli_stmt_bind_param($stmt, "i", $userID);
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $name);
mysqli_stmt_fetch($stmt);
if (!empty($name)) {
echo '{"name": ' . $name . '}';
} else {
echo '{"name": "Anonymous" }';
}
} else {
// No results!
echo "No results";
}
}
}

Execute Multiple Queries in PHP with NULL as an Input Parameter

EDIT (2011-07-23)
Have gotten some very helpful answers, both of which I've tried implementing. But I can't seem to get back the id from my Get_Security statement. I'm pretty sure my problem is that, in my first call statement Get_Security, the last three parameters are set to NULL. Seems like other people have the same problem. Doesn't seem like there's much documentation on having NULL as an input. How does one go about this?
NEW CODE
$stmt = mysqli_stmt_init($link);
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to prepare statement. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
}
mysqli_stmt_close($stmt);
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'mypath-to-database-link'; //this gets $link
$stmt = mysqli_stmt_init($link);
$sql = "CALL Add_Active('$id','Research')";
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to prepare statement Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'mypath-to-database-link'; //this gets $link
$sql = "INSERT INTO MyTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
$stmt = mysqli_stmt_init($link);
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to INSERT INTO Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
ORIGINAL ENTRY
Searched extensively (e.g. PHP Manual, SO questions) but answers are confusing.
I need to execute 3 of SQL statements in a row:
Call stored procedure Get_Security that takes some inputs and returns an array, including the id.
Call another stored procedure Add_Active that takes the returned id from Get_Security as an input.
Insert some variables into my table.
Problem: I'm getting the MySQL Error Number 2014: "Commands out of sync; you can't run this command now".
I know I have to use mysqli_stmt_prepare, mysqli_stmt_execute, and mysqli_stmt_close to resolve this, but it's very confusing how to do this.
Would very much appreciate help in how to translate this using the above functions.
CODE:
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Get_Security.';
include '../error.html.php';
exit();
}
while($row = mysqli_fetch_array($result)){
$tags[] = array('id' => $row['id']);
}
foreach ($tags as $tag){
$id = $tag['id'];
}
$sql = "CALL Add_Active('$id','Research')";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
$sql = "INSERT INTO MyTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
if (!mysqli_query($link, $sql)){
$error = 'Error adding submitted tag into Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
I hope this helps. From what I can tell you aren't doing anything too fancy, so this should suffice. PDO does also support IN/OUT params to stored procedures as well, but I didn't see you using them.
Please note, PDO handles errors in different ways depending on how it is initialized. So I've skipped error handling here. Please let me know if you have questions.
Also note that until you add a DSN (MySQL's for example) this code doesn't care what database type it is, so the DSN can be a config value making your code more portable. I'm sure you could also see how this code could easily be expanded into a class/model structure (specifically the security check SP could become a PHP method)
$db = new PDO(); // http://www.php.net/manual/en/pdo.construct.php for params
// These generate PDO_Statement (see: http://www.php.net/manual/en/class.pdostatement.php)
$securityStmt = $db->prepare("CALL Get_Security( ?, ?, ?, ?, ? )");
$addActiveStmt = $db->prepare("CALL Add_Active( ?, ? )");
$insertStmt = $db->prepare("INSERT INTO MyTable SET id=?, open_items=?, attachments=?");
// Security CALL
$securityStmt->bindParam( 1, $symbol, PDO::PARAM_STR );
$securityStmt->bindParam( 2, $tagName, PDO::PARAM_STR );
$securityStmt->bindParam( 3, NULL, PDO::PARAM_NULL );
$securityStmt->bindParam( 4, NULL, PDO::PARAM_NULL );
$securityStmt->bindParam( 5, NULL, PDO::PARAM_NULL );
$securityStmt->execute();
// Bind the ID to a variable is useful sometimes...
$securityStmt->bindColumn( 'id', $securityId );
$securityStmt->fetch( PDO::FETCH_BOUND );
/*
Insert + Active call
These are much simpler because we don't need to set the data types of the input
(they are all string I hope...you didn't mention what the last 2 were in the insert).
*/
$addActiveStmt->execute(
array(
$securityId,
'Wedge Research'
)
);
$insertStmt->execute(
array(
$securityId,
$openItems,
$attachments
)
);
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "CALL SOMETHING()");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
mysqli_stmt_close($stmt);
So I've figured out how to solve this with my original code by simply closing the link to the database after every query. I would love to do prepared statements instead, but at least this works.
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Get_Security.';
include '../error.html.php';
exit();
}
while($row = mysqli_fetch_array($result)){
$tags[] = array('id' => $row['id']);
}
foreach ($tags as $tag){
$id = $tag['id'];
}
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "CALL Add_Active('$id','Research')";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "INSERT INTO myTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
if (!mysqli_query($link, $sql)){
$error = 'Error adding submitted tag into Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}

Categories