2016-09-07 157 views
0

我的工作將使用表單數據到MySQL數據庫,插入數據時,它給的我不確定指數 的錯誤消息,有人可以幫 預先感謝您PHP插入數據到MySQL數據庫,顯示錯誤

<?php 
$servername = "localhost"; 
$username = "jad"; 
$password = "jad"; 
$dbname = "info"; 
// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 

// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

// Attempt insert query execution 
if (isset($_POST['submit'])) { 
$fname = $_POST['first_name']; 
$lname = $_POST['last_name']; 

$sql = "INSERT INTO names (first_name, last_name) VALUES ('$_POST[fname]', '$_POST[lname]')"; 
if(mysqli_query($conn, $sql)){ 
    echo "Records added successfully."; 
} else{ 
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn); 

} 
} 
// Close connection 
mysqli_close($conn); 
?> 

<html> 
<body> 
<form action = "" method = "POST"> 
first name : <input type = "text" name = "fname"> 
<br><br> 
last name : <input type = "text" name = "lname"> 
<br><br> 
<input type = "submit" name="submit" value="submit"> 
</form> 
</body> 
</html> 
+0

沒有輸入存在一個名爲「FIRST_NAME」或「姓氏」(例如'$ _ POST [「FIRST_NAME」] '拋出一個「未定義索引」錯誤)。 – showdev

回答

0

這應該工作,但請注意,你很容易受到SQL注入,這是非常糟糕的。

$sql = "INSERT INTO names (first_name, last_name) VALUES ('$fname', '$lname')"; 

我建議您閱讀以下內容,讓自己熟悉預處理語句: http://php.net/manual/en/mysqli.prepare.php

+0

非常感謝,我會試試看 –