PHP mysqli help with binding var in code block? - php

I am pretty new to prepared statements, I am currently working through all my code to update it.
I need a bit of help rewriting the following code:
if($stmt = $db->query("select * from product where active=1 and id=?")){
echo "Returned Result";
}else{
echo "Invalid SQL";
}
Using this code I need to bind the variable $_POST['id']:
$stmt->bind_param("s", $_POST['id']);
where would I place the bind to get the whole code block to work?
thanks in advance

Instead of query() you need to call prepare():
// Prepare the statement first and bind params
$stmt = $db->prepare("select * from product where active=1 and id=?")){
$stmt->bind_param("s", $_POST['id']);
// Then execute it
if ($stmt->execute()) {
echo "Returned Result";
// Then fetch your results
} else {
echo "Query failed";
}

Related

get results of query using prepared statements mysqli

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

Login PDO script gives an error of `Call to a member function blind_param() on boolean`

I have this login code while I tried exactly what the tutorial said, yet it gave me this error :
Call to a member function blind_param() on boolean
The code goes as:
<?php
include ('db.php');
$sql = "SELECT id FROM users WHERE email = ?"."AND password = ?";
$stmt = $conn->prepare($sql);
$stmt->blind_param('ss',$_POST['email'],$_POST['password']);
$stmt->execute();
$stmt->blind_result($id);
if($stmt->fetch())
{
echo 'loggin in';
} else {
echo 'try again';
}
Any Help is Greatly Appreciated..
$stmt -> bindParam(1,$_POST['email']);
$stmt -> bindParam(2,$_POST['password']);
For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
see:http://php.net/manual/en/pdostatement.bindparam.php
You query missing a space between ? and AND :
$sql = "SELECT id FROM users WHERE email = ? "."AND password = ?";
So, $conn->prepare($sql); fails and $stmt is false.
You should ever test the results of the functions :
$stmt = $conn->prepare($sql);
if (!$stmt) { /* handle error */ }
else {
$stmt->bind_param(...);
}
NB: PDO uses bindParam(), MySQLi uses bind_param() and bind_result().

Passing variable from URL + Selecting from SQL and Echoing it

Title is a little hard to understand, so basically I'm making a Pastebin clone and am attempting to do a kind of viewmember.php?id=1213 thing for viewing pastes. However, I can't figure it out at all. I've done a lot of research, and after finally understanding what I had to do (or so I thought) I made this up and don't know why it isn't working.
<?php
require 'connection.php';
$getid = $_GET["id"];
$sql = "SELECT * FROM pasteinfo WHERE id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $getid);
echo $stmt;
?>
I'm probably just stupid. Thanks for the help.
You need to run the command to execute the query.
$sql = "SELECT field1, field2 FROM pasteinfo WHERE id = ?"; // Specify fields in query
$stmt->bind_param("i", $getid); /* bind parameters for markers */
$stmt->execute(); /* execute query */
$stmt->bind_result($field1, $field2); /* bind result variables */
$stmt->fetch(); /* fetch value */
echo "Field 1:".$field1;
echo "Field 2:".$field2;
Reference: Example #1 mysqli::prepare() example
// save result in a variable and then run a loop and echo
$result = $stmt->execute();
foreach($result as $val){
echo $val->item_name;
}

Error with bind_param() when updating a record in mysql database

Why am I getting the error below? The code works, and updates the database like it should It just gives me this error. I'm pretty new to PHP so please forgive me ignorance.
mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of
variables doesn't match number of parameters in prepared statement
here are my code:
<?php
require_once('connection.inc.php');
$conn = dbConnect('write');
// prepare SQL statement
$sql = "UPDATE reimbursements
SET presidentstatus='$p_submit',
treasurerstatus='$t_submit',
checknumber='$check_submit',
paid='$paid_submit'
WHERE id='$id'";
$stmt = $conn->stmt_init();
$stmt = $conn->prepare($sql);
// bind parameters and insert the details into the database
$stmt->bind_param('ssss', $p_submit, $t_submit, $check_submit, $paid_submit);
$stmt->execute();
if ($stmt->affected_rows == 1) {
$success = "Information has been updated.";
} else {
$errors[] = 'Sorry, there was a problem with the database.';
}
Thanks for any help.
You forgot to bind the $id as a parameter.
$stmt->bind_param('ssssi', $p_submit, $t_submit, $check_submit, $paid_submit, $id);
^------ (assuming id is an integer thus `i`) ^^^------- (added)

PHP PDO using try

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.

Categories