2016-12-13 29 views
0

我發現了一個addrecord.php我已經編輯添加基於現有id值,這addrecord.php是用來值添加到它已經存在的記錄的另一列,添加值基於現有ID

樣品,從下面的表中,Column1和Column2已經有一個現有的值,我想通過向Column3添加一個值爲New3的值來編輯表,但它似乎沒有更新表。

Column1 | Column2 | Column3 | Column4 

Exist1 | Exist2 | New3 | New4 

我曾嘗試使用編輯選項,而不是增加基於現有id的記錄,但問題還是一樣,不增加新的記錄。

這裏是我的HTML,

<tr> 
<td>New3:<strong><span style="color: #ff0000;">*</span></strong></td> 
<td colspan="2"><input type="text" name="new3" style="width: 220px;" value=""/></td> 
</tr> 
<tr> 
<td>new4:<span style="color: #ff0000;"><strong>*</strong></span></td> 
<td colspan="2"><input type="text" name="new4" style="width: 220px;" value="<?php echo $_SESSION['name']; ?>" readonly="readonly"/></td> 
</tr> 
<tr> 
<td>new5:<span style="color: #ff0000;"><strong>*</strong></span></td> 
<td colspan="2"><select name="new5" style="width: 224px;"> 
       <option value="" selected="selected">Please select...</option> 
       <option value="New5Option">New5Option</option> 
       <option value="New5Option2">New5Option2</option> 
       <option value="New5Option3">New5Option3</option> 
       <option value="New5Option4">New5Option4</option> 
       </select></td> 
</tr> 

這是我的PHP,

if (isset($_POST['submit'])) 
{ 
// get the form data 
$id = $_POST['id']; 
$new3 = $_POST['new3']; 
$new4 = htmlentities($_POST['new4'], ENT_QUOTES); 
$new5 = htmlentities($_POST['new5'], ENT_QUOTES); 

// check that firstname and lastname are both not empty 
if ($new3 == '' || $new4 == '' || $new5 == '') 
{ 
// if they are empty, show an error message and display the form 
$error = 'ERROR: Please fill in all required fields!'; 
renderForm($new3, $new4, new5, $id); 
} 
else 
{ 
// insert the new record into the database 
if ($stmt = $mysqli->prepare("INSERT testtable (new3, new4, new5) VALUES (?, ?, ?) WHERE id=?")) 
{ 
$stmt->bind_param("sssi", $new3, $new4, $new5, $id); 
$stmt->execute(); 
$stmt->close(); 
} 
// show an error if the query has an error 
else 
{ 
echo "ERROR: Could not prepare SQL statement."; 
} 

// redirect the user 
header("Location: new_statuslist.php"); 
} 

} 
// if the form hasn't been submitted yet, show the form 
else 
{ 
renderForm(); 
} 

// close the mysqli connection 
$mysqli->close(); 
?> 
+1

「WHERE」子句作爲SQL的一部分無效INSERT ... VALUES '聲明。 SQL'INSERT'語句將一行(或多行)添加到表中。使用SQL UPDATE語句修改已存在的行。 (MySQL還提供了一個特殊的'INSERT ... ON DUPLICATE KEY UPDATE'語句,它可以方便用於某些用例。) – spencer7593

回答

0

看代碼,現在看來,這始終執行insert。如果你想然後更新現有的行,你需要這樣的執行查詢:

update table set Column3 = ?, Column4 = ?, Column5 = ? where Column1 = ? and Column2 = ?

它將更新值,並給你的更新記錄的計數。如果要插入的記錄不存在,那麼可以檢查記錄計數並在插入查詢爲0的情況下執行插入查詢。

+0

我也試過這個'UPDATE',但它仍然沒有更新記錄, 'if($ stmt = $ mysqli-> prepare(「UPDATE testtable SET new3 =?,new4 =?,new5 =?,comments =?WHERE id =?」)) {stmt-> bind_param(「ssssi」,$ new3, $ new4,$ new5,$ id); $ stmt-> execute(); $ stmt-> close();' – testyummy

+0

你可以檢查傳遞給該查詢的參數值嗎?也許它無法找到記錄,因此不會更新它。 –

+0

現在很好,感謝檢查,但我不小心刪除了'if(isset($ _ GET ['id']))''因此它沒有更新記錄。 – testyummy