how to update empty value with bind parameters in php mysqli - php

I am creating message delete script in PHP MYSQLI. I have added zero value to update column. my script is working but I want to add zero value with bind parameters.
Here is my source code
<?php
require_once "config.php";
if (isset($_GET['to_id'])) {
$id = $_GET['to_id'];
$session_id = $_SESSION['userid'];
}
$stmt = $con->prepare("UPDATE pm SET from_delete = '0' WHERE id = ? AND from_id = ?");
$stmt->bind_param("ss", $id, $session_id);
if ($stmt->execute()) {
echo"deleted successfully";
} else {
echo "Failed to delete<br/>";
}
?>

Just add another placeholder ? and bind value to it:
$stmt = $con->prepare("UPDATE pm SET from_delete = ? WHERE id = ? AND from_id = ?");
$zero = '0';
$stmt->bind_param("sss", $zero, $id, $session_id);

Related

What is the proper way to bind to different values in PDO equal to mysqli?

I have been converting a small login script i did to PDO trying to give it a try.
Code mysqli
$stmt = $conn->prepare('SELECT id, name FROM users WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name);
if ($stmt->fetch()) {
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
I changed to PDO
$sql = "SELECT id, name FROM users WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->execute();
if ($stmt->fetch())
{
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
in mysqli i was able to bind and store $id and $name but read those were not available in PDO
$stmt->store_result();
$stmt->bind_result($id, $name);
There's no equivalent of bind_result in PDO because you don't really need it. Just read the data from the row:
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row["id"];
$_SESSION['name'] = $row["name"];
$is_valid = true;
}
You also don't need the $stmt->bindParam(':name', $name); line because there is no :name input parameter in your SQL.
More examples are available in the manual and elsewhere.
See also Is it possible to use store_result() and bind_result() with PHP PDO? for more useful background info.
The equivalent method is called bindColumn(). You can bind a variable to one column in the result set.
/* Bind by column number */
$stmt->bindColumn(1, $id);
$stmt->bindColumn(2, $name);
while ($stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $id. "\n";
}
However, I would recommend writing simpler code. PDO is designed to be easier to use.
If you want to make the code simpler, use arrays. The method fetch() returns an array with the current row. They are better when you need to fetch more than one column from the result. If you only need to fetch one column, use fetchColumn().
$sql = "SELECT id, name FROM users WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute([
'id' => $id,
'name' => $name,
]);
if ($row = $stmt->fetch()) {
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}

getting session into each page

i want to insert into a table depending on the id of the session:
here the code in class.php:
public function activate($activation, $id,$change,$userID){
$stm1= $this->conn->prepare("INSERT INTO `log` (`date`,`change`) VALUES(CURRENT_TIMESTAMP(),'$change') WHERE `user_id` =$userID");
($stm1->execute());
$stmt = $this->conn->prepare("UPDATE `segments` SET `activation` = '$activation' WHERE `id` = '$id'")
or die($this->conn->error);
if ($stmt->execute()) {
$stmt->close();
$this->conn->close();
return TRUE;
}
}
at the top of the page i have this:
require './config.php';session_start();$userID = $_SESSION['user_id'];
and in action.php where the action go i have this:
$conn = new db_class();
$conn->activate($activation, $id,$change,$userID);
echo "Updated successfully.";
exit;
the first query insert into log is not working \ please help
This should be a comment but I don't have the rep yet...
Primarily, you don't do that type of insert with a WHERE clause. The insert will fail.
As an aside, that insert is open to sql injection. Bind your your parameters. Also, you should add error handling. If you had that, you would see the insert fails. Quick example (1 way...there are other ways...and I assumed $change is a string and $userId is an int...)
$sql = 'INSERT INTO log
SET `date` = CURRENT_TIMESTAMP(),
change = :change,
user_id = :user_id;';
$stmt = $this->conn->prepare( $sql );
$stmt->bindParam( ':change', $change, PDO::PARAM_STR );
$stmt->bindParam( ':user_id', $userID, PDO::PARAM_INT );
$result = $stmt->execute();
if (!$result) {
// failure -> get and handle the error
$error_array = $stmt->errorInfo();
} else {
// do something
}
The docs can help > pdo::execute, pdo::errorinfo

how to perform value calculation in mysql database using php

i have a column inside my user table named pairCount which has a value of 2 by default, but whenever an action occur, i want the value to be minus by one (1). so i wrote the following code
<?php
session_start();
require_once './include/Constants.php';
require_once './include/DatabaseConn.php';
require_once './vendor/autoload.php';
require_once './include/User.php';
require_once './include/Level.php';
use \phputil\JSON;
$user = User::getCurrentUser();
$db = new DatabaseConn();
$link = $db->connect();
$sql = "update users set `payee-1` = NULL, status = ?,`pairCount` = ? WHERE `payee-1` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param('sss', $status, $pairCount, $payee1);
$status = PAIR;
//here is were i did the calculation, but it given me error
$pairCount = $pairCount (-1);
$payee1 = ($user->getUserName());
$res = $stmt->execute();
$stmt->store_result();
if ($res) {
echo "<h1>Congrate you have successfully unsubscribe to a pay this person";
header('Refresh: 3;url=icant3.php');
} else {
echo 'undone';
}
It is also possible to do that in your SQL query.
update users set `payee-1` = NULL, status = ?, `pairCount` = pairCount - 1 WHERE `payee-1` = ?
Then you don't need to do anything with $pairCount variable in your PHP code.

Update an enum type

This is my Code:
public function enUser($userID) {
try {
$userStatus = "Y";
$tokenCode = "";
$sql = ('UPDATE tbl_users SET userStatus = ? AND tokenCode = ? WHERE userID = ?');
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $userStatus);
$stmt->bindParam(2, $tokenCode);
$stmt->bindParam(3, $userID);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
This is my enum in database
I have try more to edit it. But in database always appear nothing. I mean in the field 'userStatus' after running the update script, its just value like "" (empty). Can any one help me? Thanks.
You update must be:
'UPDATE tbl_users SET userStatus = ?, tokenCode = ? WHERE userID = ?
See the comma instead of AND
And make sure that $userID exists in your DB

Why MySQLI prepare is failing but no errors is being reported

I am stuck up as to why my Update prepare statement is failing but though I do not see any SQL error:
<?php
include(dirname(__FILE__).'\config.php' );
$id = $_POST['id'] ;
$value = $_POST['value'] ;
$column = $_POST['columnName'] ;
$columnPosition = $_POST['columnPosition'] ;
$columnId = $_POST['columnId'] ;
$rowId = $_POST['rowId']
$response['status']='';
$mysqli = new mysqli($sql_details['host'],$sql_details['user'],$sql_details['pass'],$sql_details['db']);
$mysqli->autocommit(FALSE);
$stmt = $mysqli->stmt_init();
if ($stmt = $mysqli->prepare("UPDATE users SET ? = ? where id = ?")) {
$response['status']='OK';
//$stmt->bind_param("ssi", $column, $value, intval(ltrim(substr($id, -4),'0')));
//$stmt->execute();
//$response['status'] = $mysqli->affected_rows;
//if ($mysqli->affected_rows == 1 )
//$response['status'] = 'success';
$stmt->close();
//if (!$mysqli->commit())
//$response['status'] = 'fail';
$mysqli->close();
}
else
$response['status']=$mysqli->error;
}
echo json_encode($response);
?>
Even though I have commented most of the lines and expect to the conditional string 'OK' at my UI side - I never ever see that . No errors is also reported - what am I doing wrong?
It seems that the UPDATE prepared statement works fine when in case of column name is present rather than a bind value like the below one works:
if ($stmt = $mysqli->prepare("UPDATE users SET first_name = ? where id = ?"))
Is there any way to have it the way I have requested?

Categories