Akshay Sargar Akshay Sargar - 5 months ago 15
SQL Question

Store 2 inputs having same name into 1 'address' column of the database

I have two address inputs

'address1'
and
'address2'
having the same name as 'address[]' . I want to put the value of both the inputs in a single address column of the database but the problem is that data of only 2nd input is being stored into the database.

index.php




$addressData = $_POST['address'];
foreach ($addressData as $addressValue) {
$query = "INSERT INTO `users` (`name` ,`address` , `birthdate` ,`age` , `coach` , `phone`,`email` ,`password`)
VALUES ( '".mysqli_real_escape_string($link, $_POST['name'])."' , '".mysqli_real_escape_string($link, $addressValue)."' ,'".mysqli_real_escape_string($link, $_POST['birthdate'])."' ,'".mysqli_real_escape_string($link, $_POST['age'])."' , '".mysqli_real_escape_string($link, $_POST['coach'])."' , '".mysqli_real_escape_string($link, $_POST['phone'])."' , '".mysqli_real_escape_string($link, $_POST['email'])."' , '".mysqli_real_escape_string($link, $_POST['password'])."')";
}

<div class="form-group row">
<label class="col-sm-2 form-control-label">Address1</label>
<div class="col-sm-10">
<input type="text" id="address" class="form-control" name="address[]" placeholder="Home address">
<span class="fa fa-map-marker"></span>
</div>
</div>

<div class="form-group row">
<label class="col-sm-2 form-control-label">Address2</label>
<div class="col-sm-10">
<input type="text" id="address2" class="form-control" name="address[]" placeholder="City,Pincode....">
<span class="fa fa-map-marker"></span>
</div>
</div>




Answer

It is because you do insert inside the foreach loop. If you want the address to be saved on a single table, you might want to combine the address first and do insert outside the foreach loop. See the updated code below

$addressData = $_POST['address']; 

$address = "";
foreach ($addressData as  $addressValue) {
    $address .= "\n" . $addressValue;
}               
$query = "INSERT INTO `users` (`name` ,`address` , `birthdate` ,`age` , `coach` , `phone`,`email` ,`password`)

           VALUES ( '".mysqli_real_escape_string($link, $_POST['name'])."' ,
                    '".mysqli_real_escape_string($link, $address)."' ,
                    '".mysqli_real_escape_string($link, $_POST['birthdate'])."' ,
                    '".mysqli_real_escape_string($link, $_POST['age'])."' ,
                    '".mysqli_real_escape_string($link, $_POST['coach'])."' ,
                    '".mysqli_real_escape_string($link, $_POST['phone'])."' ,
                    '".mysqli_real_escape_string($link, $_POST['email'])."' ,
                    '".mysqli_real_escape_string($link, $_POST['password'])."'   )";
Comments