Question

I'm trying to create a SQL query using PHP in which it checks to see if a row has already been submitted/set using the same date and user name. If it hasn't it inserts a new row. If it does find a match, it updates the row instead.

I can insert a new row fine, but when I use a pre-existing date and name, I receive no error in any of my logs, and the query appears to run without any problems. But when checking the database, I notice that there are no UPDATES actually set to the row. When I run the update command manually in SQL, it appears to work fine.

Having no logs/error data to go on, I was hoping to get some advice here. I'm sure there must be something I'm missing here. This is what I'm currently using:

require_once 'db-conn.php';

$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$var4 = $_POST['var4'];

$conn = db_connect (); 
$sqlq = "SELECT * FROM tbl WHERE date = '$date' AND name = '$name'"; 
$nRows = $conn->query("$sqlq")->fetchColumn();

if ($nRows==0) {
try {
  $sqli = "INSERT INTO tbl (name,email,date,var1,var2,var3,var4) VALUES (:name,:email,:date,:var1,:var2,:var3,:var4)";
   $sql = $conn->prepare("$sqli");
   $sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3 ':var4' => $var4));
 } catch(PDOException $e) {
   die ('SQL Error');
   }
 }
else {
 try {
  $sqli = "UPDATE tbl SET email='$email', notes='$notes', var1='$var1', var2='$var2', var3='$var3' WHERE date='$date' AND name='$name'";
  $sql = $conn->prepare("$sqli");
  $sql->execute(array($name, $email, $date, $var1, $var2, $var3, $var4));
} catch(PDOException $e) {
  die ('SQL Error');
}

}

Was it helpful?

Solution

You don't have the bound variables correct:

$sqli = "UPDATE tbl SET email=:email, notes=:notes, var1=:var1, var2=:var2, var3=:var3 WHERE date=:date AND name=:name";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3, ':notes'=>$notes));

You did it correct in the Insert statement but not in the update.

Not sure where you are getting $notes from though.

Plus not sure if it is intentional or not but you are not updating var4 in the update query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top