通过PHP通过HTML表单显示和更新MYSQL数据

时间:2019-01-03 18:32:12

标签: php html mysql database forms


我试图弄清楚如何在一个页面中显示数据库表的所有行,所有值都是可编辑的,并且在其末尾只有一个提交按钮。我知道了一半的方程式,但是由于某种原因,它仍然不起作用。
我目前所拥有的是一个显示MYSQL表所有内容的表,并且所有字段都是可编辑的。每个字段都有一个提交按钮(不是我想要的,但愿意的话愿意解决),但是在编辑数据库字段中的内容时,它带我到一个页面,该页面给我一个语法错误: br /> “错误更新记录:您的SQL语法有错误;请在与MySQL服务器版本相对应的手册中找到在第1行的'WHERE idnum ='0000'附近使用的正确语法”

以下是来自FORM.PHP

<?php
include('config.php');
$result = mysqli_query($connect,"SELECT * FROM table123");
?>
<html>
<table>
<?php while ($res = mysqli_fetch_array($result)) { ?>
<tr>
        <form action="test.php" method="post">
            <td><input type="text" name="ret" value="<?php echo $res['ret']; ?>"></td>
            <td><input type="text" name="code" value="<?php echo $res['code']; ?>"></td>
            <td><input type="text" name="status" value="<?php echo $res['status']; ?>"></td>
            <td><input type="hidden" name="idnum" value="<?php echo $res['idnum']; ?>"></td>
            <td><input type="submit" name="update" value="Submit"></td>
        </form>
    </tr>
    <?php } ?>
</table>
</html>

以下是来自TEST.PHP

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$connect = mysqli_connect($servername, $username, $password, $dbname);
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['update'])) {
$sql = "UPDATE ssoretailerlist SET ret = '$_POST[ret]', code = '$_POST[code]', status = '$_POST[status]', WHERE idnum = '$_POST[idnum]'";
} else {
echo "Nothing was posted";
}
if (mysqli_query($connect, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connect);
}
mysqli_close($connect);

1 个答案:

答案 0 :(得分:-1)

语法错误是因为您有多余的逗号。在WHERE之前删除逗号,您应该没事。

$sql = "UPDATE ssoretailerlist
        SET ret = '$_POST[ret]', code = '$_POST[code]', status = '$_POST[status]'
        WHERE idnum = '$_POST[idnum]'";

每个字段都有一个提交按钮。无需创建新表单并为循环中的每一行提交,而是在循环外手动进行一次。

<?php
include('config.php');
$result = mysqli_query($connect, "SELECT * FROM table123");
?>
<html>
<table>
<form action="test.php" method="post">
<?php while ($res = mysqli_fetch_array($result)) { ?>
    <tr>
    <td><input type="text" name="ret" value="<?php echo $res['ret']; ?>"/></td>
    <td><input type="text" name="code" value="<?php echo $res['code']; ?>"/></td>
    <td><input type="text" name="status" value="<?php echo $res['status']; ?>"/></td>
    <td><input type="hidden" name="idnum" value="<?php echo $res['idnum']; ?>"/></td>
    </tr>
<?php } ?>
</table>
<input type="submit" name="update" value="Submit"/>
</form>
</html>

您可能还需要处理要插入到表单中的输出。如果数据中有双引号,则可能会破坏HTML。签出htmlspecialchars()。根据您的专栏标题,我认为不会,但请始终牢记。

但是,每一行的输入名称都完全相同。这是个问题。如何知道要选择并关联的retcodestatusidnum?首先,您要turn the names into arrays。然后,您想遍历idnum数组并执行多个UPDATE查询以访问其他数组中的相同键位置。如果您无法解决此问题,请发布一个新问题。

最后,您的config.php文件很有必要。您可能要read this thread about require_once() vs include()。如果include失败,则抛出错误并进行处理是很好的选择,而不是继续处理脚本的其余部分。