使用下拉列表更新数据库而不使用提交按钮

时间:2018-02-17 05:45:46

标签: php html mysql database phpmyadmin

每当我从下拉列表中进行选择时,我都会尝试更新表status值。

问题是我的更新查询出现语法错误。我已经阅读了有关语法错误的内容,我无法理解它。我想我需要更具体的帮助。这就是我所做的:

<?php

    $hostname = "localhost";
    $username = "root";
    $password = "";
    $databasename = "companydb";

    try
    {
        $conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        if(isset($_POST["status"]))
        {
            $query = "UPDATE tickets SET status = '$status' WHERE id = $id";
            $statement = $conn->prepare($query);
            $statement->execute(array('status' => $_POST["status"]));

            $count = $statement->rowCount();
            if($count > 0)
            {
                echo "Data Inserted Successfully..!";
            }
                else
            {
                echo "Data Insertion Failed";
            }
        }
            else
        {
            echo "unknown index: 'status'";
        }
    }

    catch(PDOException $error)
    {
        echo $error->getMessage();
    }
?>

这是我的表架构:

enter image description here

2 个答案:

答案 0 :(得分:1)

您没有正确执行准备好的陈述。您需要在查询中添加占位符而不是变量。变量应添加到execute()行。

$query = "UPDATE tickets SET `status` = :status WHERE `id` = :id";
$statement = $conn->prepare($query);
$statement->execute(array(':status' => $_POST["status"],':id' => $id));

另外,仅供参考,$id未定义。

答案 1 :(得分:0)

尝试更改此内容:

$query = "UPDATE tickets SET status = $status WHERE id = $id";