-3

i have this code to update a value in the database, but this only works if there is already something in the database. is it possible to check if the database is empty first and if its empty INSTERT something into the databse, else just update it with this code.

 $name = $_POST['example'];
        if (isset($_POST['example'])) {
            $sql = 'UPDATE `table` SET `column` = "' . $name . '"';
            $stmt = $this->db->pdo->prepare($sql);
            $stmt->execute();
            return $stmt->rowCount();
        }
jarlh
  • 42,561
  • 8
  • 45
  • 63

2 Answers2

1

Try the below code. It's working for you.

<?php
    $name = $_POST['example'];
    if (isset($_POST['example'])) {
        $sql = 'SELECT COUNT(*) from `table` where `column` = "' . $name . '"';
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->execute();

        if ($stmt->fetchColumn() > 0) {
            $sql = 'UPDATE `table` SET `column` = "' . $name . '"';                
        } else {
            $sql = 'INSERT INTO `table` (`column`) VALUES("' . $name . '")';
        }
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->rowCount();
    }        
?>
Mukesh Singh Thakur
  • 1,335
  • 2
  • 10
  • 23
0

Prepare stmt for prevent sql injection like:

<?php
    $name = $_POST['example'];
    if (isset($_POST['example'])) {
        $sql = 'SELECT COUNT(*) from `table` where `column` = ?';
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->bind_param('s',$name);
        $stmt->execute();

        if ($stmt->fetchColumn() > 0) {
            $sql = 'UPDATE `table` SET `column` = ?';                
        } else {
            $sql = 'INSERT INTO `table` (`column`) VALUES(?)';
        }
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->bind_param('s',$name);
        $stmt->execute();
        return $stmt->rowCount();
    }        
?>
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34