gpt4 book ai didi

php - 如何将表单中的值存储到 mySQL 数据库中?

转载 作者:行者123 更新时间:2023-11-28 23:50:13 27 4
gpt4 key购买 nike

我制作了一个表单,我想将 cat 的输入值存储到我的 SQL 数据库中。这是我的 PHP 代码:

<?php

$cat = $_POST['cat'];

if ( !empty($_POST)) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE orders set cat = ? WHERE id = '$id'";
$q = $pdo->prepare($sql);
$q->execute(array($cat));
Database::disconnect();

}


?>

这是我的表格:

<form action="index.php" method="post">

<div id="modal-content" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">

<h3><?php echo $id ?></h3>
</div>
<div class="modal-body">
<p>
<input type="text" name="cat" />
</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>

有人知道为什么这不起作用吗?没有数据存储到数据库中。数据库连接工作正常。谢谢

**** 更新:

我发现了我的错误。这是结果:

    <?php

$cat = $_POST['cat'];
$id = $_POST['id'];

if ( !empty($_POST)) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE orders set cat = ? WHERE id = '$id'";
$q = $pdo->prepare($sql);
$q->execute(array($cat));
Database::disconnect();

}


?>

和形式

    <form action="index.php" method="post">

<div id="modal-content" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">

<h3><?php echo $id ?></h3>
</div>
<div class="modal-body">
<p>
<input type="text" name="cat" />
<input type="hidden" name="id" value="1"/>
</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>

最佳答案

如评论中所述,您有一个未定义的 $id

    $cat = $_POST['cat'];

if ( !empty($_POST)) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE orders set cat = ? WHERE id = '$id'";
$q = $pdo->prepare($sql);
$q->execute(array($cat));
Database::disconnect();

}


?>

相反,你应该:

在您的 HTML 中:

<input type="hidden" name="check"/>

然后在您的 PHP 中:

if(isset($_POST['check'])){
$cat = $_POST['cat'];
$id = $_POST['id'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE orders set cat = ? WHERE id = '$id'";
$q = $pdo->prepare($sql);
$q->execute(array($cat));
Database::disconnect();

}
?>

关于php - 如何将表单中的值存储到 mySQL 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32764599/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com