-1

I want to insert image to Database but I want to check if there is already stored image or not. If no image before, update the database, if there is image in database, update database and unlink prev image.

$stmt = $db->query("SELECT COUNT(*) FROM pr_journalist WHERE id='".$id."' AND foto='' ");
    
    
    if($stmt = 0) {
    
        // Insert image file name into database
            $insert = $db->query("UPDATE pr_journalist SET foto='".$fileName."' WHERE id='".$id."'");
        
                        
        unlink("uploads/".$foto);
           $statusMsg = 'ok';
       
        }else{
        // Insert image file name into database
            $insert = $db->query("UPDATE pr_journalist SET foto='".$fileName."' WHERE id='".$id."'");
       
                        
           $statusMsg = 'ok';
        
    }

With my above code, counting Row always make me to one if condition, although im trying to change to foto IS NOT NULL and change if condition to != 0 or foto IS NULL with if = 0. It is like if ($stmt = 0) always got the same value from row count.

Burhanuddin Rabbani
  • 349
  • 2
  • 3
  • 10
  • 1
    please use only **prepared statements with pararmeters** to prevent **sql injection** – nbk Aug 22 '20 at 17:04
  • @nbk since im new here, would you please tell me clearer? – Burhanuddin Rabbani Aug 23 '20 at 01:00
  • i gave you all buzzwords to find your way around, but the canonical to that particular idea is https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – nbk Aug 23 '20 at 11:01

1 Answers1

0

To count rows you should not do $stmt = 0,

its,

$count=query->rowCount();
niyamxsept
  • 105
  • 6
  • hello @niyamxsept thanks for your answer, should I change the select statement? or just IF statement? – Burhanuddin Rabbani Aug 23 '20 at 01:02
  • Place this statement after $stmt query then do a if check by. If ($count=0) – niyamxsept Aug 23 '20 at 07:39
  • sorry, I tried and nothing worked. If I follow you, the $stmt is not called by anything, $count=query->rowCount(); doesn't call $stmt – Burhanuddin Rabbani Aug 24 '20 at 08:04
  • ok i give you a simple example , follow the rest :) `$db=new PDO("mysql:host=localhost",dbname=yourdbname,"username","passoword"); $query=$db->query("select * from users where name=$name"); $query->execute(); $counter=$query->rowCount();` now do if($counter==0) – niyamxsept Sep 02 '20 at 20:23