我遇到了PHP和MYSQL的问题。我有一个HTML表单,提交时运行以下PHP脚本。问题是以下PHP代码将数据插入数据库两次。我认为这与以下PHP而不是数据库有关:
<?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);
?>
答案 0 :(得分:6)
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
您的代码中有mysqli_query($conn,$sql);
两次。一旦进入if(),一旦进入外部。其中每个都将插入到您的数据库中。
这里需要注意的是if中的mysqli_query
被评估 - 也就是说,它运行并且if语句在函数调用的结果上执行。因此,您无需再次调用它。
答案 1 :(得分:2)
Tushar指出了两个mysqli查询,他是对的,除此之外,现在的代码会导致安全问题,因为它允许sql注入...
请修改您的代码,如下所示:
$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']);