Php 问题插入数据库:文本和html格式
我在将数据(文本和HTML格式)插入mysql字段时遇到问题。 这里是错误Php 问题插入数据库:文本和html格式,php,mysql,syntax,insert,comma,Php,Mysql,Syntax,Insert,Comma,我在将数据(文本和HTML格式)插入mysql字段时遇到问题。 这里是错误 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 a
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…)
我想到了另一种方法,我创建了两个处理逗号、分号和斜杠的函数
以下是函数addslashes的代码:
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';
}
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
语法错误总是让我抓狂。
您能帮我吗?除非您想将字符串从拉丁语-1转换为UTF-8,否则不要使用utf8编码。
不要使用
addslashes
或依赖魔法引号;如果您无法关闭魔法引号,请关闭魔法引号或使用stripslashes
反转其效果。除非有非常具体的原因,否则不要手动替换和转义单个字符 对数据库使用适当的转义机制进行一次转义。如果您使用的是
mysql.*
(不要再使用它),请使用mysql\u real\u escape\u string
。如果您使用的是mysqli.*
,请使用mysqli\u real\u escape\u string
或更好的语句。如果您正在使用PDO,请使用准备好的语句
有关此主题的更长、更详细的讨论,请参阅
您当前的“准备好的语句”是无用的,因为它根本不会将查询与值分开。您只需像往常一样连接所有值,然后一次性强制它们通过准备好的语句。也不需要存储过程,使用客户端API可以更好地完成这一切
因此:
mysqli::insert_id
获取最后一个insert id发布实际执行的SQL查询。另外,尝试通过
mysqli\u real\u escape\u string()
传递数据。php函数中的函数escape($values.=trim($this->escape($val)…在使用mysqli\u real\u escape\u string()后返回字符串是的,PDO::quote
是PDO的\u real\u escape\u string
等价物。我总是建议使用准备好的语句,而不是转义。如果你有权访问准备好的语句,你需要一个很好的理由来使用任何转义函数。首先..谢谢你的回复。deceze,我会尝试你的建议。你应该这样做如果您正确使用mysqli
,则永远不必使用mysqli\u real\u escape\u string
。甚至暗示它具有误导性。准备好的语句是确保正确转义数据的最可靠方法。手动转义与一般应用程序代码没有任何关系。停止使用这种经典方法。您将伤害自己的数据elf.不要这样做。占位符是必不可少的。它们不可忽略。这里的示例非常复杂,很难审核。PDO提供了一种简单的方法,可以用更少的代码行来表达相同的内容。@AISSECRONOS您可以使用真正准备好的语句,即使使用mysqli,甚至使用过程mysqli。只要去做吧。