使用 PDO 进行安全可靠的面向对象插入
这段代码对 SQL 注入安全吗?它使用准备好的和参数化的语句。如果不是,那么我应该怎么做,因为我只想通过面向对象的过程来使用它,我可以在其中插入列名和列值。
<?php
class CommunItY
{
const community_host = "localhost";
const community_db = "DB";
const db_username = "root";
const db_password = "";
private $conn = null;
public $trace = "";
public function insert($table ,$values = array())
{
try{
foreach ($values as $field => $v)
{
$ins[] = ':' . $field;
}
$ins = implode(',', $ins);
$fields = implode(',', array_keys($values));
$sql = "INSERT INTO $table ($fields) VALUES ($ins)";
$ready = $this->conn->prepare($sql);
foreach ($values as $f => $v)
{
$ready->bindValue(':' . $f, $v);
}
$ready->execute();
}
catch(Exception $e){
$this->trace .= " • insertion error • ". $e->getMessage();
}
}//end of method
public function __construct(){
$connectionString = sprintf("mysql:host=%s; dbname=%s; charset=utf8",
CommunItY::community_host, CommunItY::community_db);
try {
$this->conn = new PDO($connectionString, CommunItY::db_username, CommunItY::db_password);
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} //end of connection by PDO
catch(PDOException $e){
$this->trace .= " • ". $e->getMessage();
}
}//end of construct
public function __destruct(){
$this->conn = null; //close connection
} //end of destruct
}
calling...
$call = new Contact()
$call->insert(table_x, array('col1' => 'value1', 'col2' => 'value2'));