2015-04-04 13 views
0

我想添加我的網站的「管理」部分。現在我正在開發一個部分,爲我的MySQL數據庫添加一個新行。如何使用PHP爲mySQL添加一行?

第一個文件是我的admin.php的:

<html> 
... 
<body> 
<form action="add.php" method="post"> 
    <input type="text" name="order" /> 
    <input type="text" name="newstatus" /> 
    <input type="submit" value="Add" /> 

</form> 

</body> 
</html> 

我在這裏的目標是2個數據(表只有兩列現在)添加到新行。

然後,我有我的add.php文件:

<? 
//declare my connection variables - I'll move these to a secure method later 
mysql_connect($servername, $username, $password) or die (mysql_error()); 

// Select database 
mysql_select_db($dbname) or die(mysql_error()); 

// The SQL statement is built 

$sql="INSERT INTO $tblname(id, status)VALUES('$order', '$newstatus')"; 
$result=mysql_query($sql); 

if($result){ 
    echo "Successful"; 
    echo "<BR>"; 
    echo "<a href='admin.php'>Back to main page</a>"; 
} 

else { 
    echo mysqli_errno($this->db_link); 
} 
?> 

<?php 
// close connection 
mysql_close(); 
?> 

每當我輸入的任何數據(的什麼已經是表中的非重複的),它給了我一個錯誤。如果我完全清除了所有數據的表格,則會輸入一次。我得到一個重複鍵錯誤,但我的密鑰應該是「訂單」,每次輸入時都是唯一的。

對此提出建議?

+0

建議刪除mysql_ *函數並切換到pdo,並使用預處理語句。如果你有興趣找出原因,搜索'sql injection' – 2015-04-04 18:10:44

回答

2

,你不應該把自己填寫ID,而是將其設置爲你的數據庫AUTO_INCREMENT。然後,你有沒有形成這樣:

<form action="add.php" method="post"> 
    <input type="text" name="newstatus" /> 
    <input type="submit" value="Add" /> 
</form> 

和你的PHP代碼如下所示:

$newstatus = mysql_real_escape_string($_POST['newstatus']); // note the usage of $_POST variable 
$sql="INSERT INTO `$tbl_name` (`status`) VALUES ('$newstatus')"; 
$result = mysql_query($sql) or die('Failed executing query: '.mysql_error()); 

AUTO_INCREMENT可以設置在phpMyAdmin與下面的查詢:

ALTER TABLE `WorkOrders` MODIFY `id` INTEGER NOT NULL AUTO_INCREMENT; 

最後,請勿使用mysql_*函數,they are deprecated

+0

這個也拋出了同樣的錯誤。 – jpgerb 2015-04-04 18:19:43

+0

什麼是錯誤? – D4V1D 2015-04-04 18:20:16

+0

致命錯誤:當不在對象上下文中的時候使用$ this在第27行的/home/jpegchaos/public_html/add.php中 – jpgerb 2015-04-04 18:26:41

0

我猜你的表的'id'字段是主鍵。如果是這種情況,則不能有兩行具有相同標識符的行。

由你的變量名稱newstatus,在我看來你似乎試圖更新訂單的狀態;是這樣嗎?如果是的話,你應該使用形式的UPDATE SQL查詢:如果你實際上是插入新行

UPDATE table SET status='somestatus' WHERE id=someid 
+0

我不得不稍微更新我的筆記。 「身份證」是「訂單」 - 「訂單」是我的主鍵 - 我從來沒有複製我的投入... IE:1被使用,我使用2等我試圖添加一個新行,而不是更新現有一。 – jpgerb 2015-04-04 17:59:33

+2

在執行它之前可以打印$ sql,以確保SQL查詢是您所期望的嗎? – christophetd 2015-04-04 18:01:36

+0

當我回復表單數據時,他們按我的要求出來。它們不是現有數據的重複 – jpgerb 2015-04-04 18:05:24