Stanislas Piotrowski
Stanislas Piotrowski

Reputation: 2704

Array php and database mysql saving datas

I'm having trouble with an array. It actually appears on a page: a form of several lines. Each line corresponds to a record in the database and so they all have a common denominator.

More thanks to javascript I can add fields on the fly.

The trouble I'm having is when recording data. In fact I thought at first I should delete everything, and then insert so I just the following query:

<?php if(isset($_POST['enreg']))
{

foreach($_POST['data'] as $data){
    if (!empty($data['code_s'])){
$sql2="DELETE FROM scenarii WHERE code_s='".mysql_real_escape_string($_GET['code_s'])."'";
mysql_query($sql2) or die(__LINE__.mysql_error().$sql2);    

$sql7 = '
INSERT INTO  scenarii SET 
code_s              = "'.mysql_real_escape_string($data['code_s']).'", 
titre               = "'.mysql_real_escape_string($data['titre']).'",
action              = "'.mysql_real_escape_string($data['action']).'", 
libelle             = "'.mysql_real_escape_string($data['libelle']).'",
jour                = "'.mysql_real_escape_string($data['jour']).'"' ;    
mysql_query($sql7) or die(__LINE__.mysql_error().$sql7);

    } 
  } 
}
?>

The worries is that the deleted information is not stored again (though they are in the post variable as they exist in the form of a form and are therefore the variables.

In fact it only saves the new rows from javascript.

The trouble is that I can not do an update just because there are new lines.

Upvotes: 0

Views: 143

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64496

<?php if(isset($_POST['enreg']))
{
$sql2="DELETE FROM scenarii WHERE code_s='".mysql_real_escape_string($_GET['code_s'])."'";
mysql_query($sql2) or die(__LINE__.mysql_error().$sql2);  
foreach($_POST['data'] as $data){
if (!empty($data['code_s'])){

$sql7 = '
INSERT INTO  scenarii SET 
code_s              = "'.mysql_real_escape_string($data['code_s']).'", 
titre               = "'.mysql_real_escape_string($data['titre']).'",
action              = "'.mysql_real_escape_string($data['action']).'", 
libelle             = "'.mysql_real_escape_string($data['libelle']).'",
jour                = "'.mysql_real_escape_string($data['jour']).'"' ;    
mysql_query($sql7) or die(__LINE__.mysql_error().$sql7);

} 
} 
}
?>

put your delete query before foreach loop

Upvotes: 1

Stanislas Piotrowski
Stanislas Piotrowski

Reputation: 2704

afeter several hours of testing Ive seen that the delete request was in the loop for each so it has deleted all after all reinjection that is why I only have the last input left evry time.

Now I've deleted all and reinjected all after. It works properly.

What I do not understand is that i did not see it before.

Thanks to everybody for the help.

Upvotes: 0

Related Questions