php – 使用Int Casting的PDO准备语句
我正在使用PDO预处理语句从外部xml源向数据库插入数据,因为我不信任源100%我在所有变量(包括字符串和整数)上使用了bindValue,例如:
SQL: INSERT INTO table (id,int1,int2,string1,string2) VALUES (:id,:int1,:int2,:string1,:string2) 在我的PDO功能中: $sth->bindValue(":id",$id,PDO::PARAM_INT); $sth->bindValue(":int1",$int1,PDO::PARAM_INT); $sth->bindValue(":int2",$int2,PDO::PARAM_INT); $sth->bindValue(":string1",$string1,PDO::PARAM_STR); $sth->bindValue(":string2",$string2,PDO::PARAM_STR); 现在我的问题是,如果我使用int casting来获取整数值,我是否仍然需要为整数值使用准备好的statment: $id= (int) $xml->node->attributes()->id $id将始终为整数,即使xml文件中的id不是整数,使用(int)时返回的值也将为0. 在这种情况下,这样做是否安全: INSERT INTO table (id,string2) VALUES ($id,:string2) 编辑(较短代码示例): 绑定所有参数: $sql="INSERT INTO table (id,string2) VALUES (:id,:string2)"; $pars = array(":id"=>$id,":int1"=>$int1,":int2"=>$int2,":string1"=>$string1,":string2"=>$string2); $model->insert($sql,$pars); 没有Intergers Binding: $sql="INSERT INTO table (id,string2) VALUES ($id,:string2)"; $pars = array(":string1"=>$string1,":string2"=>$string2); $model->insert($sql,$pars); 现在想象这个代码有20个参数. 解决方法
这是一个错误的问题.原因太多了.
建筑就是其中之一. 意味着像这样的代码 $model = new Model($data); $model->save(); 请参阅 – 没有跟踪也没有PDO,也没有SQL.所有数据库交互都在幕后完成.显然,无论先前的验证如何,这个DB层都应该能够正确处理数据.如果他们只为DB做了,那么后者就没用了.坦率地说,这是DB层的业务,如何格式化值,而不是程序员 整体理智是另一个. $sql = "INSERT INTO table VALUES (?,?,?)"; $pdo->prepare($sql)->execute($data); 如果您的值已经在数组中 另一个是效率. $stmt = $pdo->prepare("INSERT INTO table VALUES (?,?)"); foreach ($data as $row) { $stmt->execute($row); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |