I try to translate this query to my PDO object from this thread:
UPDATE table_name
SET col1 = <<new value>>,
col2 = <<new values>>,
last_modified_timestamp = <<new timestamp>>
WHERE primary_key = <<key column>>
AND last_modified_timestamp = <<last modified timestamp you originally queried>>
So i have a "modified" field in the mysql table and fetch the data (SELECT modified AS last_modified) to pre-fill in a hidden field in my form and post the value to the object:
$position->readOne();
$position->last_modified = $_POST['last_modified'];
<input name='last_modified' value='{$position->last_modified}'>
My object update query looks like:
UPDATE positions
SET
... some values ...
WHERE id=:id
AND modified=:last_modified
$stmt->bindParam(":last_modified", $this->last_modified);
If I check the posted variables, everything looks fine but the update query ignores my second where clause completely and override the modified field after post the form.
Sure a beginner issue but I canĀ“t find it.
Thanks
EDIT:
Select query
public function readOne(){
$query = "SELECT
p.position,
p.modified,
p.modified AS last_modified
FROM positions p
WHERE id = ?
LIMIT 0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->position = $row['position'];
$this->modified = $row['modified'];
$this->last_modified = $row['last_modified'];
}
Update query
public function updatePosition(){
$this->getTimestamp();
$query = "UPDATE positions
SET
position=:position,
modified=:modified,
WHERE id=:id
AND modified=:last_modified";
$stmt = $this->conn->prepare($query);
$this->position=htmlspecialchars(strip_tags($this->position));
$stmt->bindParam(":id", $this->id);
$stmt->bindParam(":position", $this->position);
$stmt->bindParam(":modified", $this->timestamp);
$stmt->bindParam(":last_modified", $this->last_modified);
if($stmt->execute()){
print_r($this->last_modified);
return true;
}
print_r($stmt->errorInfo());
return false;
}
public function getTimestamp(){
date_default_timezone_set('Europe/Berlin');
$this->timestamp = date('Y-m-d H:i:s');
}
I figured it out. The update query and everything else worked fine but the problem was the notification handling, so the function updatePosition() told me everything was updated but it worked as it should and it did not update anything if the value was not the same.
This fixed it:
if($stmt->execute()){
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) {
return true;
}
This helped me to understand how it works ... PDOStatement::execute() returns true but the data is not updated
Related
I want to check if user already liked the post, if so than delete the user from database likes.
I've tried to do an if statement but it wont get to the else and only add likes even when user_id and post_id are the same.
Like.class.php
private function Addlike(){
$conn = db::getInstance();
$query = "insert into likes (post_id, user_id) values
(:post_id, :user_id)";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
}
private function Deletelike(){
$conn = db::getInstance();
$query = "DELETE FROM likes WHERE post_id = :post_id
AND user_id =:user_id";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
}
public function CheckLike(){
$conn = db::getInstance();
$query = "SELECT COUNT(*) FROM likes WHERE
post_id=:post_id AND user_id=:user_id";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
if($result["COUNT(*)"] == 0){
$this->Addlike();
}else{
$this->Deletelike();
}
return $result;
}
If you press like for the first time you should like the post and it should be stored in the database, if you press again you unlike the post and it gets deleted from the database. But now it only does the Addlike function...
I think PDO::FETCH_ASSOC returns a multidimensional array when used with PDOStatement::fetchAll, according to https://www.php.net/manual/en/pdostatement.fetchall.php#refsect1-pdostatement.fetchall-examples.
Try changing your code to something like this and see if it works. You could also try dumping the $result variable to see what the structure looks like.
if($result[0]["COUNT(*)"] == 0){
$this->Addlike();
}else{
$this->Deletelike();
}
If an array index doesn't exist, PHP considers it false, which would explain why you're always adding likes, since false == 0 in PHP.
If you want to avoid this equivalency of false and 0, use the identical operator to also compare types:
if ($result["COUNT(*)"] === 0) {
...
I have an SQL table for a gallery, it has rows for id, userid, imagename.
I'm trying to write a function that calculates how many images a certain user has added, I'm new to PDO and SQL. This is what I have for my function;
// Photo Count
public function photoCount($id){
$this->db->query('SELECT * FROM gallery WHERE id = :id');
// Bind value
$this->db->bind(':id', $id);
$row = $this->db->single();
// Check row
$count = $this->db->rowCount();
return $count;
}
Do I need the line $row = $this->db->single(); or can I just return the rowCount at the moment all is being returned is 0's which is incorrect.
Any help appreciated.
Use SQL count function. If $this->db is a PDO object then...
public function photoCount($id){
$statement = $this->db->prepare('SELECT count(*) as c FROM gallery WHERE id = :id');
$statement->bindParam(":id", $id);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_OBJ);
return $result->c;
}
I have a PostgreSQL query to insert data into my table but for some reason, It's not inserting the data into the table
When I var_dump the execute statement if returning false.
foreach($information as $data){
$name = $data['name'];
$id = $data['id'];
$time = $data['time'];
$query = "INSERT INTO students(name,id,time)"
."VALUES('$name','$id','time')";
//prepare and execute
$stmt = $psql->prepare($query);
$result = $stmt->execute();
var_dump($result);
}
Most probably '$name' is not being understood in the query. Also, you should check for the existence of those variables
Try doing something like this
if (isset($name, $id, $time)) {
$query =
'DO$$
BEGIN
IF NOT EXISTS(select 1 from students where name = \'$name\')
THEN
INSERT INTO student("name", "id", "time")
VALUES (\'$name\', \'$id\', \'$time\')
END IF;
END;
$$;'
}
My goal is to update 4 column in my table in a single query.But end up only 1 column is updated,the other 3 is not.
My query is like this
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = ?,user_bio = ? ,gender = ?,date_of_birth = ? WHERE user_id = ?");
$stmt->bind_param("sssii",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
$result = $stmt->execute();
$stmt->close();
return $result;
Here is my code for the query call
//update to database
global $user_id;
$db = new DBhandler();
$update_result = $db->callForQueryFunction($user_id,$user_bio,$date_of_birth,$gender,$profile_image_string);
$response = array();
if($update_result){
$response['error'] = false;
$response['message'] ="sucess";
}else{
$response['error'] = true;
$response['message'] ="fail";
}
After I run in advanced rest client ,with the the following query
user_bio=hihi&gender=f&profile_image_string=somestringhere&date_of_birth=2015-08-16
After run the query,the result is always "success",but in Mysql table only profile_image_path column is updated,the rest 3 column user_bio,date_of_birth and gender all are not updated.
Here is my database structure
I work for hours still haven't figure it out what's wrong with the code or my database structure.
Update:
I tried with bind_param for s with $date_of_birth,but still no luck with it
$stmt->bind_param("ssssi",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
UPDATE
I actually using this example from Androidhive,the sample code is as below
/**
* Updating existing task
* method PUT
* params task, status
* url - /tasks/:id
*/
$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
// check for required params
verifyRequiredParams(array('task', 'status'));
global $user_id;
$task = $app->request->put('task');
$status = $app->request->put('status');
But I use the same method as below to grab the value,but after var_dump() all the value is NULL.Here is my code
$app->put('/updateuserdetails','authenticate',function ()use ($app){
$user_bio = $app->request()->put('userbio');
$gender =$app->request()->put('gender');
$date_of_birth = $app->request()->put('dob');
$profile_image_string = $app->request()->put('profilestring');
I try this as well.The value of user_bio,gender,date_of_birth are all still null.
$app->post('/updateuserdetails','authenticate',function ()use ($app){
$user_bio = $app->request()->post('userbio');
$gender =$app->request()->post('gender');
$date_of_birth = $app->request()->post('dob');
$profile_image_string = $app->request()->post('profilestring');
I just cant figure out what is going wrong here
Update
After I test it in Postman by send data with x-www-form-urlencoded it come out with this error,which I cant get any solution
Try the following:
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = :image, user_bio = :bio, gender = :gender, date_of_birth = :dob WHERE user_id = :id");
$stmt->bindParam(":image", $profile_image_upload_url, PDO::PARAM_STR);
$stmt->bindParam(":bio", $user_bio, PDO::PARAM_STR);
$stmt->bindParam(":gender", $gender, PDO::PARAM_STR);
$stmt->bindParam(":dob", $date_of_birth, PDO::PARAM_STR);
$stmt->bindParam(":id", $user_id, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->close();
return $result;
I have this function inside a class. The insert is like exactly the same query (but with the INSERT obviously) and it works perfect.
I am trying now to update the database with the properties that the object has and it's not updating, it echoes "Rows not updated" I have tried everything and I have compared my code with examples that work and I dont know why it's not working! It's driving me nuts.
CODE:
public function update() {
$query = "UPDATE ".$this->tablename."
SET
itemtype = :itemtype,
category = :category,
title = :title,
content = :content,
active = :active,
keywords = :keywords,
order = :order,
featured = :featured
WHERE id = ".$this->id;
$this->conn->beginTransaction();
$q = $this->conn->prepare($query);
$q->execute(array(":itemtype"=>$this->itemtype, "category"=>$this->category, "title"=>$this->title,
":content"=>$this->content, ":active"=>$this->active, ":keywords"=>$this->keywords,
":order"=>$this->order, ":featured"=>$this->featured));
if($q->rowCount() > 0) {
echo "Rows updated = ".$q->rowCount()."<br/>";
$return = true;
} else {
echo "Rows not updated<br/>";
$error = $this->conn->errorInfo();
$this->SQLerror = $error[2];
$return = false;
}
$this->conn->commit();
return $return;
}
Just know that the errorInfo returns NULL, like if there was not any SQL Sintax Error!
Put colons here:
"category"=>$this->category, "title"=>
Should be:
":category"=>$this->category, ":title"=>
Make sure, the $this->tablename and $this->id don't lead to any syntax errors.
Update
The word Order is reserved in SQL. Escape it with backticks:
`order` = :order,
You are asking if($q->$q->rowCount() > 0) before commit() see Manual