gpt4 book ai didi

php - MYSQLi 表单查询错误

转载 作者:行者123 更新时间:2023-11-29 22:25:41 25 4
gpt4 key购买 nike

我似乎找不到错误。该表单应该更新数据库中的类别。

当我尝试更新类别时,出现此错误

Notice: Undefined variable: cat_id in C:\xampp\htdocs\CMS_project\admin\categories.php on line 90 QUERY FAILED!You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

这是下面的代码,我已经注释了第 90 行在哪里。

                   <form action="categories.php" method="post">
<div class="form-group">
<label for="cat_title">Update Category</label>

<?php
if(isset($_GET['edit']))
{
$cat_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$cat_id} ";
$select_categories_id = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($select_categories_id))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
?>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" name="cat_title" class="form-control">


<?php } } ?>

<?php
if(isset($_POST['update_category']))
{
$the_cat_title = $_POST['cat_title'];

//Below is line 90

$query = "UPDATE categories SET cat_title = '{$the_cat_title}' WHERE cat_id = {$cat_id} ";
$update_query = mysqli_query($connection, $query);
if(!$update_query)
{
die("QUERY FAILED!" . mysqli_error($connection));
}
}
?>

</div>
<div class="form-group">
<input type="submit" name="update_category" value="Update Category" class="btn btn-primary">
</div>

</form>

这是表单获取 ID 的地方

    <?php
while($row = mysqli_fetch_assoc($select_categories))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<tr>
<td>{$cat_id}</td>
<td>{$cat_title}</td>
<td><a href='categories.php?delete={$cat_id}'>Delete</a></td>
<td><a href='categories.php?edit={$cat_id}'>Edit</a></td>
</tr>";

}
?>

最佳答案

$cat_id 变量根本没有在查询范围内定义。这意味着, $cat_id 变量仅在 if 语句中声明,您检查 $_GET['edit'] 是否已设置。要修复此问题,请将带有类别 id 的隐藏字段添加到您的表单中,然后在 PHP 中添加:

$cat_id = $_POST['cat_id'];

就在第 90 行之前。

顺便记住使用 mysqli_real_escape_string 来防止 SQL 注入(inject)问题。

关于php - MYSQLi 表单查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30285264/

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