[英]syntax error in converting varchar into int
I am getting this error 我收到此错误
Error: 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 '(int) , (int)' at line 2
I followed up this answer on SO 我在SO上跟进了这个答案
I am getting base and limit as string , i want to convert them into int. 我正在获取base和limit作为字符串,我想将它们转换为int。 This is my code
这是我的代码
$category = $_POST['category'];
$base= $_POST['base'];
$limit= $_POST['limit'];
$sql = "SELECT id, name, url
FROM OBJECTS where CATEGORY='$category' limit (int)$base , (int)$limit";
You will need to cast it. 您将需要进行投射。 What you are doing now is PHP casting.
您现在正在做的是PHP转换。 you will have to cast it in the SQL statement.
您将不得不将其强制转换为SQL语句。
$category = $_POST['category'];
$base= $_POST['base'];
$limit= $_POST['limit'];
$sql = "SELECT id, name, url
FROM OBJECTS where CATEGORY='$category' limit CAST($base AS UNSIGNED) , CAST($limit AS UNSIGNED)";
Use casting like this, 使用这样的转换,
$category = $_POST['category'];
$base= intval($_POST['base']);
$limit= intval($_POST['limit']);
//OR
/*
$base= (int)($_POST['base'];
$limit= (int)($_POST['limit'];
*/
$sql = "SELECT `id`, `name`, `url`
FROM `OBJECTS` where CATEGORY='$category' limit $base ,$limit";
PHP variable interpolation will not fill that in when in a string. 当在字符串中时,PHP变量插值将不会填充。
You need to do it like this 你需要这样
$sql = "SELECT id, name, url FROM OBJECTS where CATEGORY='$category' limit ".(int)$base." , ".(int)$limit;
Interpolation only works on variables ( or things that start with the $ ) such as accessing a class ( which is in a variable ) so things like this 插值仅适用于变量(或以$开头的事物),例如访问类(位于变量中),因此类似
echo "self::$STATIC";
will look for $STATIC
as a variable. 将查找
$STATIC
作为变量。 Essentially you are putting this if $v = 1 本质上,如果$ v = 1,则将其放入
"(int)$v" becomes "(int)1"
And subsequently, MySql looks at (int)1
as a string and blows up. 然后,MySql将
(int)1
视为字符串,然后崩溃。
MySql does not have type cast in PHP manner. MySql没有以PHP方式进行类型转换。 So
(int)$base
is wrong syntax. 因此
(int)$base
是错误的语法。
First type cast, than place to query: 第一种类型转换,而不是要查询的位置:
$base = intval($base);
$limit = intval($limit);
$sql = "SELECT id, name, url FROM OBJECTS where CATEGORY = '{$category}' limit {$base}, {$limit}";
Consider using prepared statements instead of placing variables directly to query and not escaping them. 考虑使用准备好的语句,而不是直接将变量放置在查询中并且不要转义它们。
use intval in php...ref.link http://php.net/manual/en/function.intval.php
在php中使用intval ... ref.link
http://php.net/manual/en/function.intval.php
$category = $_POST['category'];
$base= intval($_POST['base']);
$limit= intval($_POST['limit']);
$sql = "SELECT id, name, url
FROM OBJECTS where CATEGORY='$category' limit $base , $limit";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.