如何在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
提交
取消