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'));