Reputation: 483
I am having trouble with PHP and MYSQL. I have an HTML form which when submitted runs the following PHP script.The problem is that the following PHP code is inserting the data into the database twice. I think it is something to do with the following PHP and not the database:
<?php
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$display_name = $_POST['displayname'];
$email = $_POST['email'];
$password = $_POST['password'];
$add_line1 = $_POST['addline1'];
$add_line2 = $_POST['addline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
$sql = "INSERT INTO members (memberID,
memberPassword,
memberFirstName,
memberLastName,
memberAddressLine1,
memberAddressLine2,
memberCity,
memberCounty,
memberPostcode,
memberDisplayName)
VALUES ('$email',
'$password', '$first_name', '$last_name',
'$add_line1', '$add_line2','$city',
'$county', '$postcode', '$display_name')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
echo 'Guest Added';
mysqli_close($conn);
?>
Upvotes: 0
Views: 1929
Reputation: 2210
Tushar pointed out the twin mysqli queries and he is right, besides that, the code as is now will cause you security troubles since it allows sql injection...
Please modify your code as follows:
$first_name = mysqli_escape_string($conn, $_POST['firstname']);
$last_name = mysqli_escape_string($conn, $_POST['lastname']);
$display_name = mysqli_escape_string($conn, $_POST['displayname']);
$email = mysqli_escape_string($conn, $_POST['email']);
$password = mysqli_escape_string($conn, $_POST['password']);
$add_line1 = mysqli_escape_string($conn, $_POST['addline1']);
$add_line2 = mysqli_escape_string($conn, $_POST['addline2']);
$city = mysqli_escape_string($conn, $_POST['city']);
$county = mysqli_escape_string($conn, $_POST['county']);
$postcode = mysqli_escape_string($conn, $_POST['postcode']);
Upvotes: 1
Reputation: 8049
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
You have mysqli_query($conn,$sql);
in your code twice. Once in the if(), and once outside. Each of these will insert into your database.
The point to note here is that the mysqli_query
inside the if is evaluated - that is, it is run and the if statement executes on the result of the function call. Thus, you do not need to call it again.
Upvotes: 7