简体   繁体   中英

php pdo : update + insert and then select returns null

For some reason this php code on execution is returning NULL...cud any1 kindly help in correcting it?

public function like($pid)
        {
             $uid = escape($_SESSION['user']);
             $sql = $this->_db->prepare("UPDATE postsinitial SET likes = likes+1 WHERE pid = :m;INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (:k, :m)");
             $sql->bindValue(':k', $uid);
             $sql->bindValue(':m', $pid);
             $sql->execute();

             $query = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = :n");
             $query->bindParam(':n', $pid);
             $query->execute();
             while($rows = $query->fetch())
             {
                return $rows['likes'];
             }

         }

But when i run the two parts of the query separately, ie, commenting out the $sql batch of code and running $query batch alone, it works and returns a value.. , it works fine..but not combined as stated..so how do i run it as is?

I've tried this model too for the select query bt still same result:

$query = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = :n");
             $query->bindParam(':n', $pid);
             $query->execute();
             while($rows = $query->fetch(PDO::FETCH_ASSOC))
             {
                return $rows[0]['likes'];
             }

The answer is simple:

You should run your queries one by one instead of stuffing them all into a single call. Run your insert query separated rom update and you'll be fine.

     public function like($pid)
     {
         $sql = "UPDATE postsinitial SET likes = likes+1 WHERE pid = ?";
         $this->_db->prepare($sql)->execute($_SESSION['user']);

         $sql = "INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (?, ?)";
         $this->_db->prepare($sql)->execute([$_SESSION['user'], $pid]);

         $stmt = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = ?");
         $stmt->execute([$pid]);
         return $stmt->fetchColumn();
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM