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
Related
I would like to get the results of a query using prepared statements but I don't get anything.
The problem is I'm not able to fetch my results. Can some one show an example how to get results of query using prepared statements?
Here is my code:
$sql = "SELECT `username` FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$statement->execute();
$statement->bind_result($user);
while ($statement->fetch())
{
printf("%s", $user);
}
Looks pretty close. I added two lines. One line stores the result and the other is a check to make sure you had a response from the query. Run it and see if it helps.
$sql = "SELECT `username` FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$statement->execute();
$statement->store_result(); //<-- Added this.
if($statement->num_rows === 0) exit('No rows');//<--Test to see if you have a result.
$statement->bind_result($user);
while ($statement->fetch())
{
printf("%s", $user);
}
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>";
}
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.
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();
I'm using statements to protect against sql injections... My question is what do i need to repeat when looping multiple queries?
If you look at the second query, im not sure if the prepare statement needs to be insde the foreach loop
Something wrong with this summary code?
open database connection
// connect to database
$conn = connect('r');
launch first query
$sql = "SELECT ... FROM ... WHERE xxx = ?";
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('i', $albumid);
$stmt->bind_result(..., ...);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
if ($num_rows > 0) {
loop results...
}
$stmt->free_result();
second query with repeats:
$sql = "SELECT ... FROM ... WHERE xxx = ?";
$stmt = $conn->stmt_init();
$stmt->prepare($sql); ///??????? inside or outside foreach loop ?????
foreach (... as $key => ...) {
$stmt->bind_param('i', $key);
$stmt->bind_result(...);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
if ($num_rows > 0) {
loop results...
}
$stmt->free_result();
}
close database
// close database
$conn->close();
You don't have to prepare the query multiple times. Just bind the parameters and execute it multiple times.
From the PHP Manual:
For a query that you need to issue multiple times, you will realize
better performance if you prepare a PDOStatement object using
PDO::prepare() and issue the statement with multiple calls to
PDOStatement::execute().
Hope this helps.