如何在MySQL INSERT语句中包含PHP变量我试图在Content表中插入值。如果在值中没有PHP变量,它可以正常工作。当我把变量$type内部值,这是行不通的。我做错什么了?$type = 'testing';mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");
3 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
字符串应该用引号括起来。 因此,这些引号应该在数据中转义,以及一些其他字符,使用 mysql_real_escape_string()
$type = 'testing';$type = mysql_real_escape_string($type);$reporter = "John O'Hara";$reporter = mysql_real_escape_string($reporter);$query = "INSERT INTO contents (type, reporter, description) VALUES('$type', '$reporter', 'whatever')";mysql_query($query) or trigger_error(mysql_error()." in ".$query);// note that when running mysql_query you have to always check for errors
要添加一个数字,必须显式地将其转换为它的类型。
$limit = intval($_GET['limit']); //casting to int type!$query = "SELECT * FROM table LIMIT $limit";
要添加标识符,最好从某种类型的白名单中选择它,由硬编码的值组成
if ($_GET['sortorder'] == 'name') { $sortorder = 'name';} else { $sortorder = 'id';}$query = "SELECT * FROM table ORDER BY $sortorder";
使一切简单化
$type = 'testing';$reporter = "John O'Hara";pquery("INSERT INTO contents (type, reporter, description) VALUES(?s, ?s, ?s)", $type, $reporter,'whatever');
添加回答
举报
0/150
提交
取消