2013-03-18 70 views
0

我遇到了PHP和MYSQL的問題。我有一個HTML表單,它在提交時運行以下PHP腳本。問題是以下PHP代碼將數據插入數據庫兩次。我認爲這是值得做下面的PHP,而不是數據庫:在你的代碼PHP在MYSQL數據庫中插入兩個重複行

<?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); 

?> 

回答

6
if (!mysqli_query($conn,$sql)) 
{ 
    die('Error: ' . mysqli_error($conn)); 
} 
mysqli_query($conn,$sql); 

你有mysqli_query($conn,$sql);兩次。一旦進入if(),並且一次在外面。其中每個將插入到您的數據庫。

這裏要注意的一點是,if中的mysqli_query被評估 - 也就是說,它被運行並且if語句對函數調用的結果執行。因此,您不需要再次調用它。

+0

是; ''mysqli_query($ conn,$ sql);'可以被刪除,只需在'if'語句中添加'else {}',並在那裏回顯'客戶添加'消息',作爲成功的指標。 – 2013-03-18 22:29:37

+0

感謝您的幫助 - 沒有意識到它在評估時運行。 – underflow 2013-03-18 22:35:54

2

圖莎爾指出了雙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']); 
+1

偉大的建議 - 新的PHP和良好的安全實踐。 – underflow 2013-03-18 22:44:36