0

I have a query that will update a row in the database, which works fine providing there is a row there to begin with.

How could I say; update if exists insert if doesn't?

    require_once('../scripts/includePDO.php');

    $who = $_SESSION['who'];
    $formText = $_POST['protext'];

$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";

    $q   =  $conn->prepare($sql);
    $q->bindValue(':who',$who,PDO::PARAM_INT);
    $q->bindValue(':formText',$formText,PDO::PARAM_STR);
    $q->execute();

header("Location: ../settings/?status=Done");
Elaine Adams
  • 179
  • 10

3 Answers3

0

Assuming user_id is a unique key in the db:

$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
dave
  • 62,300
  • 5
  • 72
  • 93
0

Your SQL query should be:

INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText

This is assuming that user_ID is a unique id

Just Lucky Really
  • 1,341
  • 1
  • 15
  • 38
0

1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).

Amin Arab
  • 530
  • 4
  • 19