[英]How to insert text and html format data into a MySQL database via PHP?
我在將數據(文本和 HTML 格式)插入 MySQL 字段 LONGTXT 時遇到問題。 這是錯誤
public 'error' => string '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 ''<p>
Haec subinde Constantius audiens et quaedam referente Thalassio doc' at line 1' (length=226)
錯誤,幾乎清楚。 我使用了所有的保護功能(編碼格式、引用、禁用html...)我想到了另一種方法,我創建了兩個處理逗號、分號和斜杠的函數。 這是函數addlashes的代碼:
FUNCTION addText($txt)
{
IF(get_magic_quotes_gpc()==false)
{
RETURN utf8_encode(addslashes($txt));
}else{
RETURN utf8_encode($txt);
}
}
保護逗號功能:
FUNCTION protect_virgules($txt)
{
IF($txt!='')
{
$x = strlen($txt);
$newTxt = '';
FOR($i=0;$i<=$x;$i++)
{
IF($txt[$i]==',' || $txt[$i] == ';')
{
$newTxt.= '\\'.$txt[$i];
}
else
{
$newTxt.=$txt[$i];
}
}
RETURN htmlentities($newTxt);
}
else
RETURN '0';
}
插入php函數:
public function insert($table,$data){
$this->last_insert_id = NULL;
$fields = "";
$values = "";
foreach($data as $fld => $val){
$values .= trim($this -> escape($val)).",";
$fields .= $fld.",";
}
$values = '"'.substr($values,0,strlen($values)-1).'"';
$fields = '"'.substr($fields,0,strlen($fields)-1).'"';
$tab=array($this->escape($table),$fields,$values,"@last_id");
$this->CALL_SP("sp_insert",$tab);
if ( $result = mysqli_query( $this->linkId, "SELECT @last_id AS last_inserted_id" ) ) {
while ($row = mysqli_fetch_assoc($result))
{
$this->last_insert_id = $row['last_inserted_id'];
}
}
return $this->queryId;
}
插入 SQL 過程代碼:
BEGIN
SET @stmt_sql=CONCAT("INSERT INTO ", tableName, " (",fields,")VALUES(", param ,")");
PREPARE stmt FROM @stmt_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT LAST_INSERT_ID() into last_id;
END
語法錯誤總是扼住我的喉嚨。 請問你能幫幫我嗎?
不要utf8_encode
,除非您想將字符串從 Latin-1 轉換為 UTF-8。
不要使用addslashes
或依賴魔術引號; 如果您無法關閉魔術引號,請關閉魔術引號或使用stripslashes
來反轉它們的效果。
不要手動替換和轉義單個字符,除非您有非常具體的原因。
使用適合您的數據庫的轉義機制進行一次轉義。 如果您正在使用mysql_*
(不再使用它),請使用mysql_real_escape_string
。 如果您使用mysqli_*
,請使用
的准備好的語句。 如果您使用 PDO,請使用准備好的語句。mysqli_real_escape_string
或更好
有關該主題的更長、更詳細的討論,請參閱The Great Escapism(使用文本中的文本需要知道的內容) 。
您當前的“准備好的語句”是無用的,因為它根本沒有將查詢與值分開。 您只是像往常一樣連接所有值,然后一次性強制它們通過准備好的語句。 也不需要存儲過程,這都可以使用客戶端 API 更好地完成。
所以:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.