Fergal O'Hanlon Fergal O'Hanlon - 2 months ago 15
jQuery Question

first form submit insert row subsequent submits update the same row

Does anyone have another solution to my problem.

When my submit button is clicked first I want to insert the row in the MYSQL database. But the form validates entry for errors so if errors are found then the user would have to click the submit button again. Now I want to update the row in the database.

I was using session variable to achieve this but I cannot now as the website uses a Realex payment gateway so I have no way to unset the session when payment is successful as this code is on their site.

So here is what I had:

if(!isset($_SESSION['jid']))
{
$sql = "INSERT INTO ...";
$result = $db->query($sql);
if($result === false)
sql_failure_handler($sql, $db->error);
$jid = $db->insert_id;
$_SESSSION["jid"] = $jid;
}
else
{
$sql = "UPDATE ... WHERE ID = '$_SESSION['jid']";
$result = $db->query($sql);
if($result === false)
sql_failure_handler($sql, $db->error);
}
}


This code is to give an idea of what I need.

I was thinking of using a post variable:

if(empty($_POST['jid'])) // insert on first click of one of the buttons
{
$sql = "INSERT INTO table ...";
$result = $db->query($sql);
if($result === false)
sql_failure_handler($sql, $db->error);
$jid = $db->insert_id;
}
else
{
$sql = "UPDATE table SET ... WHERE ID = '" . $db->real_escape_string($_POST['jid']) . "'";
$result = $db->query($sql);
if($result === false)
sql_failure_handler($sql, $db->error);
}


and then have a hidden variable but not sure this will work. Maybe a jquery to set the jid value initially?

Answer

Hidden field is a good option.

Include an empty hidden field in your form:

<input type="hidden" name="jid" value="" id="jid">

In PHP. If $_POST['jid'] is blank, insert your new row and return a response with the ID of the newly created row:

$sql = "INSERT INTO table...";
$result = $db->query($sql) or die('Errant query:  '.$sql);
$newid = $db->insert_id;
header('Content-type: application/json');
echo '{"message":"new field added", "id":"'.$newid.'"}';

On the client, if a successful post. Update the value of your hidden field ie

$('#jid').val(response.id)

Subsequent posts will now have the jid

Another option:

IN PHP, Check if the ID already exists in the DB if no insert, if yes update.

$sql = "SELECT id FROM table WHERE id = '$jid' LIMIT 1";
$result = $db->query($sql) or die('Errant query:  '.$sql);
$row_cnt = $result->num_rows;

if($row_cnt > 0){
  UPDATE
}
else{
  INSERT
}
Comments