INSERT查询在PHP中失败

时间:2014-07-18 21:54:35

标签: php mysql sql sql-insert

我确定这是一个非常明显的拼写错误,但我无法看到它。我试图使用PHP将使用POST从HTML表单中获取的数据插入到MySQL数据库中。 POST成功,但查询失败;我检查了表格,确保没有插入任何新内容。

这是用于运行查询的PHP代码:

if ($_POST) {
    $username = "root";
    $password = "root"; //ssh don't tell
    $hostname = "localhost";

    $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
    $dbname = "asoiaf";
    $tablename = "charlist";

    $id = '3';
    $bookIntroduced = $_POST['bookIntroduced'];
    $pageIntroduced = $_POST['pageIntroduced'];
    $forename = $_POST['forename'];
    $surname = $_POST['surname'];
    $oldSurname = $_POST['oldSurname'];
    $alias = $_POST['alias'];
    $title = $_POST['title'];
    $pageIntroduced = $_POST['regnalNumber'];

    // Below is the query that fails to execute.

    $query = "INSERT INTO $tablename (
            $id, $bookIntroduced, $pageIntroduced, $title, $forename, $surname, $oldSurname, $alias, $regnalNumber
            )";

    mysql_query($query) or die("Nah, I don't feel like being helpful.");

    mysql_close($dbhandle);
}

以下是DESCRIBE命令给出的表的结构:

enter image description here

任何人都可以帮我确定问题吗?

另外,如果不清楚,我是PHP和SQL的新手。

1 个答案:

答案 0 :(得分:3)

执行这样的SQL查询在许多方面都是不好的做法,尤其是因为它非常脆弱和不安全,但我认为如果添加VALUES并引用字符串,它将起作用。

$query = "INSERT INTO $tablename VALUES (
        '$id', '$bookIntroduced', '$pageIntroduced', '$title', '$forename', '$surname', '$oldSurname', '$alias', '$regnalNumber'
        )";

我建议不要这样做,我只是因为它是工作代码的最短路径而给出了这个答案。始终为表和列命名(INSERT INTO mytable (col1, col2) VALUES (:val1, :val2)),并将准备好的语句与mysqli一起使用。

相关问题