This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 6 years ago.
Here is my prepared statement
$stmt = $db->prepare("UPDATE user SET :property=:value WHERE `id`=:id");
$stmt->execute([':property' => $property, ':value' => $value]);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
How can I quickly verify that the query has gone through successfully?
I was thinking maybe an if() around the execute part?
Try this
if($stmt->rowCount() > 0){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
All you need to do is test the returned $stmt like this.
Remember both the prepare and the execute can fail and should be checked
$stmt = $db->prepare("UPDATE user SET :property=:value WHERE `id`=:id");
if ( $stmt == false ) {
print_r($db->errorInfo());
exit;
}
$stmt->execute([':property' => $property, ':value' => $value]);
if ( $stmt == false ) {
print_r($db->errorInfo());
exit;
}
This query will definitely fail
Now I look closer, you have a huge syntax error in the query. You cannot parameterise column or table names.
You also pave 3 parameters and only 2 values
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 1 year ago.
The question is simple, I have a small database and what I would like to compare is a specific column.
Scenario:
Using PHP to get the result from a querie and getting the value:
$sql = "SELECT verified FROM user WHERE id = ?";
$stmt->bind_param("i", $id);
$stmt->execute();
verified is a tinyint, either 0 or 1.
So how using PHP could make an if statement which compares either the result of $stmt->execute(); is 0 or 1.
<? php if(mysqli_fetch_row($stmt) == 0) {
echo "Not verified"
} else {
echo "Verified"
}
PD: What I would like to know is how to compare and operate on a SQL query.
You are almost there, jus grab result, and then compare it:
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
if($row['verified'] == 1){
echo 'verified';
}else{
echo 'not verified';
}
This question already has answers here:
delete using where and or
(4 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I'm coding a blog to get experience with php.
I want the admin to be able to delete a post, but when I click the delete-button which should actually bring me to a function that deletes the post I get the error Call to a member function execute() on boolean.
Here is the code of the postsRepository.php which interacts with the database and the function in the postsAdminController.php:
public function deletePost($id)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("DELETE * FROM `{$table}` WHERE id = :id");
$stmt->execute([
'id' => $id
]);
}
public function deletePost()
{
$id = $_GET['id'];
if ($this->postsRepository->deletePost($id)) {
header("Location: posts-admin");
return;
} else {
}
}
I've var_dumped the $id right before the $stmt, it's correct and the shown error says the it is because of $stmt->execute([.
The $stmt is stated as false when I var_dumped it, but why?
The correct syntax for DELETE is
DELETE FROM tableName WHERE ...
Remove the * in your query.
$stmt is false because "If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling)."
For more informations, check the documentation
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
Having a bit of trouble with this PHP MYSQLi script - Whenever I run the function, I always get a return value of 0, even though I have satisfied the conditions to return another value. It appears my code is failing to collect data from the table, however I can't work out why. Here's my code:
function updatePassword($username, $oldPass, $newPass, $newPassConf, $mysqli){
if($stmt = $mysqli->prepare("SELECT password FROM members WHERE email = ?")){
$username = 'user'; //Temp value just to test the statement
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($dbOldPass);
$stmt->fetch();
}
else{
return 0; // Failed to retrieve pw from DB
}
if($dbOldPass == $oldPass){
if($newPass == $newPassConf){
if($stmt = $mysqli->prepare('UPDATE members SET password=? WHERE username=?')){
$stmt->bind_param('ss', $newPass, $username);
$stmt->execute();
return 1; // Success
}
}else{
return 2; // Password and PW confirmation are wrong
}
}
}
Thanks in advance for any help you may be able to give!
In your case, the return code 0 indicates that it could not create a prepared statement.
So, either your $mysqli object is not properly connected (try checking $mysqli->error) or you are running into the common mistake of comparing a resource with false in which case, try using:
if( ($stmt = $mysqli->prepare("SELECT password FROM members WHERE email = ?")) !== FALSE )
This question already has an answer here:
PHP mysqli prepare statement not working
(1 answer)
Closed 1 year ago.
I simply want to select a bunch of fields from a data base - as I have done it a lot of times before... But somehow I get this error:
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement
But I count exactly 14 columns, so why when I add 14 variables does it throw this error?
public function get_invitation_fields()
{
$this->fields_db = array();
include('system/mysqli_db.php'); //db connection opens here
$statement="SELECT
invitation_ID,
recipient,
text,
name,
usr_ID,
deleted,
send_date,
resend_date,
last_date,
status,
register_date,
verify_date,
redeem_date
trans_ID
FROM invitations WHERE email=?";
if ($stmt = mysqli_prepare($db, $statement))
{
mysqli_stmt_bind_param($stmt, "s", $this->email);
if(!mysqli_stmt_execute($stmt))
{echo mysqli_stmt_error($stmt); echo mysqli_error($db); }
mysqli_stmt_bind_result($stmt,
$this->fields_db['invitation_ID'],
$this->fields_db['recipient'],
$this->fields_db['text'],
$this->fields_db['name'],
$this->fields_db['usr_ID'],
$this->fields_db['deleted'],
$this->fields_db['send_date'],
$this->fields_db['resend_date'],
$this->fields_db['last_date'],
$this->fields_db['status'],
$this->fields_db['register_date'],
$this->fields_db['verify_date'],
$this->fields_db['redeem_date'],
$this->fields_db['trans_ID']
); //PHP points the error to this line.
mysqli_stmt_fetch($stmt);
$this->invite_fields_db = $this->fields_db;
mysqli_stmt_close($stmt);
}
else
{
echo mysqli_stmt_error($stmt);
echo mysqli_error($db);
}
mysqli_close($db);
}
Can anyone see what's wrong?
Just don't use mysqli with it's bind_result, which indeed makes you ask other people to count your variables.
Either use PDO, which will make your code as short as
public function get_invitation_fields($email)
{
global $pdo; // connection should be opened ONCE at the beginning of the whole app
$sql = "SELECT * FROM invitations WHERE email=?";
$stm = $pdo->prepare($sql);
$stm->execute(array($email));
return $stm->fetch(); // values have to be RETURNED, not assigned
}
or at least use get_result() to get a familiar array from the query, without need of binding every variable manually, though it's not guaranteed to work.
This question already has answers here:
checking if SQL query was excuted in PDO [duplicate]
(2 answers)
Closed 9 years ago.
I would like to know how to check if the insert statement is executed or not.
my current code of checking it is this:
$query = $conn->prepare("INSERT INTO editlog VALUES('',:whoadd,:doing,NOW())");
$query-> execute(array(':whoadd' => $whoadd,':doing' => $doing));
if ($query->rowCount() > 0) {
// insert statement have been executed
}
else
{
// something went wrong
}
is there a better way than using $query->rowCount() > 0 ? I have heard that rowCount() itself runs a query to mysql database..so, what is a good alternative?
As Mark Parnell suggested, wrapping the execute call in an if statement does the trick. It might prove useful later on to set some attributes of your database object, too:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Causing PDO to throw exceptions (PDOException) in case a query fails. You can set these attributes by passing an array as fourth parameter to the constructor:
$pdo = new PDO('mysql:dbname=foobar;host=127.0.0.1','your','pass',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ'));
For example, here's a full list of all attributes that can be specified.
Check the return value of the execute call:
if ($query->execute(array(':whoadd' => $whoadd,':doing' => $doing))) {
// insert statment have been excuted
}
else
{
// something went wrong
}
PDOStatement::execute() itself will return true on success or false on failure.