提交表单时整数的输入语法无效


Invalid input syntax for integer when submitting form

我正在尝试将数据从简单表单发送到PostgreSQL数据库,但是我的服务器日志显示错误Query failed: ERROR: invalid input syntax for integer 有问题的代码部分是:

形式:

<form action="insert.php" method="post">
[removed]
Total Pages: <input type="number" name="totalPages" id="totalpages"><br><br>
<input type="submit"> </form>

插入中的行.php在错误消息中指示:

pg_query("INSERT INTO books(coverurl, title, author, genre, totalpg)
VALUES('".$_POST['coverURL']."','".$_POST['title']."','".$_POST['author']."','".$_POST['genre']."','".$_POST['totalpages']."')");

在网上环顾四周,我发现了提到不正确使用'"符号的解决方案,但这只会导致其他语法错误。

编辑:没有提到我的数据库中totalpg是一个小int

溶液:感谢JoDev,将'".$_POST['totalpages']."'更改为".intval($_POST['totalPages']).",现在它运行良好。

也许投

射 POST 值以确保,并删除引号:

pg_query("INSERT INTO books(coverurl, title, author, genre, totalpg)
VALUES('".$_POST['coverURL']."','".$_POST['title']."','".$_POST['author']."','".$_POST['genre']."',".intval($_POST['totalPages']).")");

[编辑]
你在HTML表单和PHP之间犯了一个错误。你的值的正确情况是:$_POST['totalPages'] P maj 中表示name属性。

您的表格是 :

Total Pages: <input type="number" name="totalPages" id="totalpages">

这个名字是好总页数...

您似乎正在尝试在数值字段中添加文本。

你试过这个吗:

pg_query("INSERT INTO books(coverurl, title, author, genre, totalpg)
VALUES('".$_POST['coverURL']."','".$_POST['title']."','".$_POST['author']."','".$_POST['genre']."',".$_POST['totalpages'].")");

如果您的字段是整数,请考虑在将值追加到查询之前使用 int 强制转换(int)。但请注意,在将所有其他变量追加到查询之前,必须对其进行转义,因为其中一个变量可能包含使查询无效的字符串。

例如,如果$_POST['title']包含值:Why Hackers Don't Want You To Escape Strings ,则查询将变为:

INSERT INTO books(coverurl, title, author, genre, totalpg)
VALUES('http://example.com/','Why Hackers Don't Want You To Escape Strings','J. Doe','Educational','400');

。这是无效的 SQL。