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);
}
Related
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
I am trying to find out how to make my code work with prepared statements. I understood the entire process up to where I commented my code. What do I have to do in order to integrate num_rows and the mysqli_query part properly?
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$query = "SELECT id FROM members WHERE name = $name AND password = $password";
$stmt = $connection->prepare($query);
$stmt->bind_param('ss', $name, $password);
$stmt->execute();
$stmt->close();
// $result = mysqli_query($connection, $query);
// $rows = mysqli_num_rows($result);
if($rows > 0){
header('location:../../success.php');
exit;
}
else {
header('location:../../failed.php');
exit;
}
}
What I tried:
$result = mysqli_query($connection, $stmt);
$rows = mysqli_num_rows($result);
Change
$query = "SELECT id FROM members WHERE name = $name AND password = $password";
to
$query = "SELECT `id` FROM `members` WHERE `name` = ? AND `password` = ?";
Adding backticks around table and columns prevents mysql reserved words error.
Remove $stmt->close();
if( $stmt->num_rows > 0 ) {
$stmt->close();
header('location:../../success.php');
exit();
} else {
$stmt->close();
header('location:../../failed.php');
exit();
}
Adding $stmt->close() inside if statement before header is best practice in this case.
Becasue adding it before if statement would result in $stmt->num_rows always returning 0; Adding it after the if statment won't work because exit() would prefent it from executing.
From the documentation:
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
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();
For best practices should I be putting the fetch command portion inside of the try statement or is the prepare and execute sufficient?
$sql = "SELECT * FROM links WHERE device = 'mobile' AND category = ? ORDER BY category asc, link_id asc";
try{
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $cat, PDO::PARAM_STR);
$sth->execute();
}
catch(\PDOException $ex){
print($ex->getMessage());
}
if($sth->rowCount()) {
print("<a data-rel=\"dialog\" data-transition=\"pop\" href=\"index.php?action=addnew&cat=$cat\">Add New Menu Item</a><br/><br/>");
print("<ul data-role=\"listview\" data-filter=\"true\">");
while($row = $sth->fetch(PDO::FETCH_BOTH)) {
print("<li>");
print("<a data-transition='fade' href='$row[$COL_HREF]'>$row[$COL_LINK_NAME]<br/></a>");
print("</li>\n");
}
print("</ul>");
}
Inside the try with the rest of the code.
If the code in your try produces an Exception, you're printing out the exception message but are then continuing to check the rowCount(), which is dependent on $sth being successfully set and executed.
Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array