根据现有ID添加值

时间:2016-12-13 16:47:51

标签: php mysql

我找到了addrecord.php我已根据现有id编辑添加值,此addrecord.php用于将值添加到已有记录的另一列,

示例,从下表中,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 个答案:

答案 0 :(得分:0)

查看代码,它似乎始终执行insert。如果要更新现有行,则需要执行以下查询:

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

它将更新值,并为您提供更新的记录计数。如果要在记录不存在时插入,则可以检查记录计数并执行插入查询(如果为0)。