Select MySqli OO with prepared statements - php

How can a SELECT statement be run with MySqli OO using prepared statements?
I am trying to learn and I could do the INSERT, DELETE, and UPDATE statements, but I have problems with SELECT. I have been searching but I still do not understand SELECT with prepared statements (read the PHP man page for prepared statements).
Without prepared statements, it works well:
$sql = "SELECT title FROM test
WHERE id = 2";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["title"] . "<br>";
}
$conn->close();
With prepared statements:
What I tried does not work.
I think I have problems with showing the data in this case. Can someone explain it please?
$stmt = $conn->prepare("SELECT title
FROM test
WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 18;
$stmt->execute();
$stmt->bind_result($title);
while($stmt->fetch()) {
echo $row["title"] . "<br>";
}
$stmt->close();
$conn->close();

It makes me wonder why you weren't able make it to the end of example and started devising a syntax of your own. What do you think bind_result($title) is for? And where did you get $row from?
$stmt = $conn->prepare("SELECT title FROM test WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 18;
$stmt->execute();
$stmt->bind_result($title);
while($stmt->fetch()) {
echo $title . "<br>";
}

Related

store sql statement in MySQL then run it

Is it possible to store the following SQL statement in MySQL then run it in a prepared statement?
Mysql table:
Table name: mystatements
Columns:id, statements
The following syntax is stored in the statements field:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret
FROM TABLE_1
Now in php:
first: I do a select query to get my statement
$stmt = $mysqli->prepare("SELECT statements FROM mystatements limit 1");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$statement.=$row['txtstatement'];
}
second: using the variable ($statement) from the the query above and add it to query below to run the in the prepared statement:
$key='password123';
$stmt = $mysqli->prepare($statement);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['txtsecret'];
}
Also my stored syntax contains AES_DECRYPT(secret,'$key') just to complicate things. is what i'm trying to achieve possible? have I gone about this completely the wrong way?
Ok..
$key='password123';
$sql = str_replace('$key', $key, $statement); //replace $key to correct value
$stmt = $mysqli->prepare($sql);
Result:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret FROM TABLE_1
to
SELECT id, AES_DECRYPT(secret,'password123') as txtsecret FROM TABLE_1

query execution with prepared statements not working

i am using ajax to display dynamic data on my website! previously it was done using simple mysqli queries now i am improving my website's security by adding prepared statements,i have two queries one is written in mysqli and other in prepared statements here's the mysqli query
$sql = "SELECT DISTINCT model_trim FROM `tbl_02_models` WHERE model_year='$year' and model_name='$model' and model_make_id='$make' ";
$run = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($run)) {
if($row['model_trim']){
$data2[$i]['model_trim']=$row['model_trim'];
$i++;
}
}
and here's the prepared statement query
$query="SELECT DISTINCT model_trim FROM `tbl_02_models` WHERE model_year=? and model_name=? and model_make_id=?";
$stmt = $db->prepare($query);
if($stmt){
$stmt->execute();
$stmt->bind_param("iss",$year,$model,$make);
$stmt->bind_result($model_trim);
while ($stmt->fetch())
{
if($model_trim)
{
$data2[$i]['model_trim']=$model_trim;
$i++;
}
}
$stmt->close();
}
the query written in simple mysqli is working fine but when i am using the same query in prepared statements it is returning me null! any idea?
Execute method is called after bind the comments.
Try below code :
$query="SELECT DISTINCT model_trim FROM `tbl_02_models` WHERE model_year=? and model_name=? and model_make_id=?";
$stmt = $db->prepare($query);
if($stmt){
$stmt->bind_param("iss",$year,$model,$make);
$stmt->bind_result($model_trim);
$stmt->execute();
while ($stmt->fetch())
{
if($model_trim)
{
$data2[$i]['model_trim']=$model_trim;
$i++;
}
}
$stmt->close();
}
For more reference follow this link - http://www.w3schools.com/php/php_mysql_prepared_statements.asp

MySQL BETWEEN with PDO prepared statements

I have a query involving a BETWEEN statement and cannot see how to bind the parameters for it:
try {
include("../epsadmin/connectpdo.php");
$sql="SELECT * FROM properties
WHERE location LIKE :location
AND bedrooms LIKE :bedrooms
AND category LIKE :category
AND price BETWEEN :minPrice and :maxPrice
ORDER BY postcode";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':location', $_REQUEST['location'], PDO::STR);
$stmt->bindParam(':bedrooms', $_REQUEST['bedrooms'], PDO::STR);
$stmt->bindParam(':category', $_REQUEST['category'], PDO::STR);
//bindParam for price BETWEEN minPrice and MaxPrice needed
$stmt->execute();
$total = $stmt->rowCount();
$obj = $stmt->fetchObject();
}//end try
catch(PDOException $error) {
$send='DB Query failed: ' . $error->getMessage();
header("Content-type: text/plain");
echo $send;
exit;
}
Could anybody help with the required bindParam statement?
how to do the prepared statement for a query involving a BETWEEN statement
Exactly the same way as with any other query: By adding the necessary placeholders to the query and then by binding them using the bindParam method.

What is the fetch_array equivelant in prepared statements?

I use fetch_array(MYSQLI_ASSOC) with query but it doesn't work with prepared statements. What is the equivalent of that in prepared statements?
Here it is:
$query = "SELECT `users` FROM `table` WHERE `country` = :country";
$stmt = $pdo->prepare($query);
$stmt->execute(array(
':country' => $country
));
$result = $stmt->fetch(PDO::FETCH_ASSOC); // Here you define how results are fetched
or you can define default FETCH MODE to be an associate array, like this:
$pdo = new PDO(...);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$result = $stmt->fetch(); // The same thing now
In addition to the accepted PDO solution, here is one for mysqli:
The first thing to keep in mind is that mysqli prepared statements do not require results to be bound:
Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt_get_result() returns a buffered result set.
So, for example:
$sql = 'SELECT * FROM mytable ORDER BY column LIMIT ?,' . SOME_CONSTANT;
Once you have bound and executed your statement, you can call get_result():
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $int) || die($db->error);
$stmt->execute() || die($db->error);
$result = $stmt->get_result();
At this point we are functionally equivalent to:
if ($result = $db->query($sql)) {
And can call our familiar fetch_array:
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$results[] = $row;
}
Instead of closing the result as we would in the non-prepared equivalent, we close the statement:
$stmt->close();

fetch() not returning first row

I am trying to update code that has been written using prepared statements. This is my first time using them and I am having difficulty retrieving all the results. When I use a direct SQL statement, it works so I don't think that's the problem.
The code will not return any results until there are at least two that match the query, then it will return all but the first row. I tried using fetchAll, but that gives different error about a call to an undefined method.
Thanks in advance for any help that you can provide. If it's not to much to ask, please provide example or reference I can refer to and complete my understanding.
function html_competitive_make_gallery ($init) {
global $USER;
$user_id = $USER->id;
$page_name = 'competitive';
$base_name = $init['base_name'];
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->bind_param('is', $user_id, $page_name);
$stmt->execute();
$stmt->bind_result($form_id,$community_id);
$stmt->fetch();
$stmt->close();
$sql = "SELECT data FROM tester WHERE type= '".$base_name."'
AND form_id= '".$form_id ."' AND community_id= '". $community_id ."' LIMIT 5";
$stmt = $link->prepare($sql);
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch();
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
$html[]='</div>';
return implode ( $html);
}
You're running fetch() before entering your loop, hence dropping the first row of your results:
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch(); // <<< THIS LINE SHOULD NOT BE HERE
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
Try this:
while ($data = $stmt->fetch()){
echo $data;
}
$stmt->close();
Your main problem is called "mysqli".
You will face such problems as long as you're using mysqli with prepared statements.
Just quit it and use PDO:
function html_competitive_make_gallery ($init) {
global $USER;
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->execute(array($USER->id, 'competitive'));
return $stmt->fetch();
}

Categories