[英]SQL Insert query in function
我有這個PHP函數:
function InsertQuery($table, $cols, $values) {
global $conn;
$InsertQuery_Sql = "INSERT into $table (" . implode(",", $cols) . ") values (" . implode("','", $values) . "'') ";
echo $InsertQuery_Sql;
$InsertQuery_Rs = mysql_query($InsertQuery_Sql, $conn);
}
我在這里調用函數:
$cols = array("ticketnumber", "status");
$values = array("1234", "Open");
InsertQuery('tickets', $cols, $values);
SQL看起來像:
INSERT into tickets (ticketnumber,status) values (1234','Open'')
這會產生錯誤,因為有一個額外的'最后,我怎么能阻止這種情況發生?
您在查詢結束時添加了''
自己”。 編輯
$InsertQuery_Sql="INSERT into $table (".implode(",", $cols).")
values (".implode("','", $values)."'') ";
^^
your culprit
並將''
替換為'
:
$InsertQuery_Sql="INSERT into $table (".implode(",", $cols).")
values (".implode("','", $values)."')";
編輯
雖然這是關於''
的問題的答案,但事實上你的代碼在其他方面也很糟糕:你不應該使用mysql
擴展,因為它已被棄用 - >使用mysqli
或更好的PDO
。 您應該在使用之前轉義任何傳遞的值(請參閱mysqli_real_escape_string()
,否則您很容易受到SQLInjection攻擊。
至於缺乏開放'
- 只需添加它:
$InsertQuery_Sql="INSERT into $table (".implode(",", $cols).")
values ('".implode("','", $values)."')";
必須有一個'
之前
$InsertQuery_Sql="INSERT into $table (".implode(",", $cols).") values ('".implode("','", $values)."') ";
使用自定義函數來內爆並包裝值:
function implode_wrapped($before, $after, $glue, $array)
{
$out = '';
foreach ( $array as $item ){
$out .= $before.$item.$after.$glue;
}
return substr($out, 0, -strlen($glue));
}
$InsertQuery_Sql="INSERT into $table (".implode_wrapped('`', '`', ',', $cols).") values (".implode_wrapped("'", "'", ',', $values).") ";
您還應該停止使用mysql_函數並切換到mysqli_,或者更優選的是,切換到PDO。
使用過程樣式mysql_命令是舊的並且已棄用; 你根本不應該使用它們。
雖然@Marcin Orlowski確實舉了一個如何解決這個問題的例子; 他並沒有真正解決你的代碼中的任何其他問題。 即使使用他的代碼,取決於$values
來源,您的ccode對MySQL注入完全開放。
我建議將代碼庫重寫為使用MySQLi和預處理語句。 請參閱快速入門指南 。
//編輯這樣的函數..
function InsertQuery($table, $cols, $values) {
global $conn;
$InsertQuery_Sql = "INSERT into $table (" . implode(",", $cols) . ") values ('" . implode("','", $values) . "') ";
echo $InsertQuery_Sql;
$InsertQuery_Rs = mysql_query($InsertQuery_Sql, $conn);
}
嘗試這個
$InsertQuery_Sql = "INSERT into $table (" . implode(",", $cols) . ") values ('" . implode("','", $values) . "') ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.