编辑表格PHP PDO [英] Edit Form PHP PDO
问题描述
我在SQL Server数据库中有一个表。我创建了一个 edit.php,可以在其中更新数据库。使用PDO建立数据库连接。
I have a table in SQL Server database. I created an "edit.php" where we can update the database. The database connection is established using PDO.
表中有很多 Null
值。当我单击编辑选项时,表格弹出。如果我完全填写了记录,则数据库将得到更新。否则,我会收到此错误消息。
I have a lot of Null
values in the table. When I click "Edit" option, the form pops out. If I completely fill the records, the database gets updated. Otherwise I get this error message.
SQLSTATE [42000]:[Microsoft] [用于SQL Server的ODBC驱动程序11] [SQL Server]错误将数据类型nvarchar转换为数字。
SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Error converting data type nvarchar to numeric.
edit.php的代码如下:
The codes for my edit.php are included below:
require_once('database.php');
if (isset($_POST['btn_submit'])) {
$id = $_POST['txt_id'];
$site = $_POST['txt_site_code'];
$location = $_POST['txt_location_name'];
try {
$stmt = $conn->prepare("UPDATE MATRIX SET Site_Code=:site, Location_name=:location
WHERE OBJECTID =:id");
$stmt->execute(array(':site' => $site, ':location' => $location,':id' => $id));
if ($stmt) {
header('Location:index.php');
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
$object_id = '';
$site = '';
$location = '';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $conn->prepare("SELECT * FROM MATRIX WHERE OBJECTID=:id");
$stmt->execute(array(':id' => $id));
$row = $stmt->fetch();
$object_id = $row['OBJECTID'];
$site = $row['Site_Code'];
$location = $row['Location_name'];
}
?>
<h2>Edit the records</h2>
<form action="" method="post">
<table border="3px" cellpadding="5px">
<tr>
<td>Site Code</td>
<td><input type="text" name="txt_site_code" value="<?= $site; ?>"></td>
</tr>
<tr>
<td>Location Name</td>
<td><input type="text" name="txt_location_name" value="<?= $location; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="txt_id" value="<?= $object_id; ?>"></td>
<td><input type="submit" name="btn_submit" value="Submit"></td>
</tr>
</table>
</form>
感谢您的帮助。
推荐答案
您必须防止php接收到空数据。
You have to prevent null datas, received by php.
示例:
$site = '';
if(isset($_POST['site'])) {
$site = $_POST['site'];
}
在更新数据库之前,为每个要保护的值执行此操作。
Do it for each value you want to protect before update your database.
这篇关于编辑表格PHP PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!