2014-02-24 49 views
3

我試圖使用這個代碼from,當頁面被加載時,它會將空字段插入到數據庫中,然後如果表單字段被填寫並且提交查詢被按下,那麼它會向數據庫發送另一批數據(MySQL) 。在提交表單之前,Php會將數據插入到數據庫中,爲空值?

<html> 
<body> 

<form action="insert.php" method="post"> 
Firstname: <input type="text" name="firstname"> 
Lastname: <input type="text" name="lastname"> 
Age: <input type="text" name="age"> 
<input type="submit"> 
</form> 

</body> 
</html> 
<?php 
$con=mysqli_connect("example.com","peter","abc123","my_db"); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$sql="INSERT INTO Persons (FirstName, LastName, Age) 
VALUES 
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; 

if (!mysqli_query($con,$sql)) 
    { 
    die('Error: ' . mysqli_error($con)); 
    } 
echo "1 record added"; 

mysqli_close($con); 
?> 
+0

時頁面加載,代碼運行。代碼插入值即使爲空 - 解決方案,插入之前提交的檢查表格 – 2014-02-24 00:59:15

回答

4
<html> 
<body> 

<form action="insert.php" method="post"> 
Firstname: <input type="text" name="firstname"> 
Lastname: <input type="text" name="lastname"> 
Age: <input type="text" name="age"> 
<input type="submit" name="submit" value="submit" /> 
</form> 

</body> 
</html> 
<?php 
if($_POST['submit']){ 
    $con=mysqli_connect("example.com","peter","abc123","my_db"); 
    // Check connection 
    if (mysqli_connect_errno()) 
    { 
     echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

    $sql="INSERT INTO Persons (FirstName, LastName, Age) 
     VALUES 
     ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; 

    if (!mysqli_query($con,$sql)) 
    { 
     die('Error: ' . mysqli_error($con)); 
    } 
     echo "1 record added"; 

    mysqli_close($con); 
} 
?> 

你必須檢查($ _ POST [ '提交'])變量的值集。

還需要一定的價值和名稱添加到您的輸入類型=「提交」 HTML元素

<input type="submit" name="submit" value="Submit!" /> 
+2

也可能不建議初級輸入'$ _POST'數據直接進入數據庫#justsaying –

1

把你插入代碼JN if語句,如:

如果(isset($ _ POST)){ 代碼在這裏 }

2

您需要檢查你的提交按鈕的isset()插入,否則它會在每個負載插入一個空行,所以添加它

</body> 
</html> 
<?php 

if(isset($_POST['submit'])) 
{ 
    $con=mysqli_connect("example.com","peter","abc123","my_db"); 

    //all your code here 
} 

請注意,您的提交按鈕是m伊辛名稱,以便將其更改爲

<input type"submit" name="submit"> 
相關問題