编辑表格 PHP PDO

Edit Form PHP PDO

我在 SQL 服务器数据库中有一个 table。我创建了一个 "edit.php",我们可以在其中更新数据库。使用 PDO 建立数据库连接。

我在 table 中有很多 Null 个值。当我点击 "Edit" 选项时,表格弹出。如果我完全填写记录,数据库就会更新。否则我会收到此错误消息。

SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Error converting data type nvarchar to numeric.

我的 edit.php 的代码如下:

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 收到空数据。

示例:

$site = '';
if(isset($_POST['site'])) {
    $site = $_POST['site'];
}

在更新数据库之前对每个要保护的值执行此操作。

如果没有提交数据而不是数值,则插入字符串值(例如“0”)。向字符串类型的列中插入数值导致的错误。