月關(guān)寶盒
2019-06-26 13:47:08
如何在MySQL INSERT語句中包含PHP變量我試圖在Content表中插入值。如果在值中沒有PHP變量,它可以正常工作。當(dāng)我把變量$type內(nèi)部值,這是行不通的。我做錯(cuò)什么了?$type = 'testing';mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");
3 回答

慕婉清6462132
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
字符串應(yīng)該用引號(hào)括起來。 因此,這些引號(hào)應(yīng)該在數(shù)據(jù)中轉(zhuǎn)義,以及一些其他字符,使用 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
要添加一個(gè)數(shù)字,必須顯式地將其轉(zhuǎn)換為它的類型。
$limit = intval($_GET['limit']); //casting to int type!$query = "SELECT * FROM table LIMIT $limit";
要添加標(biāo)識(shí)符,最好從某種類型的白名單中選擇它,由硬編碼的值組成
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');

鴻蒙傳說
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
... VALUES(testing, 'john', 'whatever')
$type = 'testing';mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");
添加回答
舉報(bào)
0/150
提交
取消