Reputation: 33
I try to insert one person detail, it's inserted successfully. If i check in DB "same data insert 3 times". Why the data insert 3 times?
I had this data in the Database.
id name dob gen
1 James 12-03-1977 M
2 James 12-03-1977 M
3 James 12-03-1977 M
PHP class
class Detail
{
function savePerson_detail($vars){
foreach($vars as $key => $value){
if(is_numeric($key) && $value >0){
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')",
mysql_real_escape_string($vars['name']),
mysql_real_escape_string($vars['dob']),
mysql_real_escape_string($vars['gen']));
mysql_query($qry) or die(mysql_error());
if($qry)
{
print 'Successfully Insert your details';
}
}
}
Html Page
<?php
$detail = new Detail();
if(isset($_POST['btnSaveDetail'])){
$detail->savePerson_detail($_POST);
}?>
Upvotes: 0
Views: 4292
Reputation: 2298
Unless I'm missing something, is this what you're trying to do?
class Detail
{
function savePerson_detail($vars) {
foreach($vars as $key => $value) {
$vars[$key] = mysql_real_escape_string($value);
}
if($qry)
{
print 'Successfully Insert your details';
}
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')";
mysql_query($qry) or die(mysql_error());
}
Upvotes: 0
Reputation: 7583
Because you used
foreach($vars as $key => $value){
When $vars
or $_POST
which was passed to it looks like this.
$_POST['name'] = 'James';
$_POST['dob'] = '12-03-1977';
$_POST['gen'] = 'M';
So it went through each of your $_POST
items 3 times.
I think you can remove the validation and do it like this.
function savePerson_detail($vars){
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')", mysql_real_escape_string($vars['name']), mysql_real_escape_string($vars['dob']), mysql_real_escape_string($vars['gen']));
mysql_query($qry) or die(mysql_error());
if($qry)
{ print 'Successfully Insert your details'; }
}
Upvotes: 0
Reputation: 197842
You actually run the query three times, that is why you insert the data three times. Just run the query one time and you should be fine.
To do this you need to change your code: First sanitize the input data in full, then run the query. You are currently picking each element of $vars
(which has three elements) and then you run the query each time.
Do one step after the other:
function savePerson_detail($vars)
{
// validate function input
foreach($vars as $key => $value)
{
if(!is_numeric($key) || !$value >0)
return;
}
// build sql query
$qry = sprintf(
"INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')",
mysql_real_escape_string($vars['name']),
mysql_real_escape_string($vars['dob']),
mysql_real_escape_string($vars['gen'])
);
// run sql query
$result = mysql_query($qry) or die(mysql_error());
// check query result
if($result)
{
print 'Successfully Insert your details';
}
}
Upvotes: 1