pdoの増删改查(修正版、前処理なし)
pdo = new PDO($dsn,$user,$pass,array(PDO::ATTR_PERSISTENT =>true)); //
}
/**
* ; update,insert ;
* @param $tableName
* @param $data
* @return mixed
*/
function filterTableColumn($tableName,$data)
{
$sql = "SELECT column_name FROM information_schema.`COLUMNS` WHERE table_name='{$tableName}' AND table_schema = '{$this->dbInfo['databaseName']}'";
$result = $this -> pdo ->query($sql);
$columns=$result->fetchAll(PDO::FETCH_ASSOC);
$fields = array();
foreach ($columns as $column) {
$fields[] = $column['column_name'];
}
// , ;
foreach ($data as $key => $value) {
if (!in_array($key,$fields)) {
unset($data[$key]);
}
}
return $data;
}
public function query($sql)
{
$queryResult =$this -> pdo -> exec($sql); // insert update ; lastInsertId ;
$this -> insertID = $this -> pdo ->lastInsertId();
$this -> affectedRows = $queryResult;
return $queryResult;
}
function getNumRows($sql)
{
$recordSet = array();
$sql = strtolower($sql);
$fromsql = explode('from', $sql);
$sql = 'select count(*) as num from'.$fromsql[1];
$tempSql = explode('limit',$sql);
$sql = $tempSql[0];
$rsArr = $this -> pdo ->query($sql);
if($rsArr){
$recordSet = $rsArr -> fetchAll(PDO::FETCH_ASSOC);
}
return $recordSet[0]['num'];
}
function insertIntoOneRecord($tableName,$dataArray)
{
$fieldArray = array();
$valueArray = array();
$dataArray = $this->filterTableColumn($tableName,$dataArray);
foreach ($dataArray as $key => $value){
if($value != ''){
$fieldArray[] = "`".$key."`";
$valueArray[] = "'".addslashes($value)."'";
}
}
$sql = "INSERT INTO `".$tableName."`
( ".implode(',', $fieldArray)." )
VALUES
( ".implode(',', $valueArray)." )";
//echo $sql;
$result = $this -> query($sql);
//echo '$result='.$result;
return $result;
}
function updateOneRecord($tableName,$dataArray,$whereArray)
{
$dataArray = $this->filterTableColumn($tableName,$dataArray);
$setArray = array();
$where = array();
foreach ($dataArray as $key => $value){
if(isset($value) && $value != '' ){
$setArray[] = "`".$key."` = '".addslashes($value)."'";
}
if ($key == 'note' && $value == null) {
$setArray[] = "`note` = ''";
}
}
foreach ($whereArray as $key => $value){
$where[]= "`".$key."` = '".addslashes($value)."'";
}
$sql = "UPDATE `".$tableName."`
SET
".implode(',', $setArray)."
WHERE
".implode(' AND ', $where);
$result = $this->query($sql);
return $result;
}
function deleteOneRecord($tableName,$whereArray)
{
$where = array();
foreach ($whereArray as $key => $value){
$where[] ="`".$key."` = '".addslashes($value)."'";
}
$sql = "DELETE FROM `".$tableName."`
WHERE
".implode(' AND ', $where);
//echo $sql;exit;
$result = $this->query($sql);
return $result;
}
public function getOne()
{
$result = $this->pdo->query($sql); // , ;
if ($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC); // , ;
}
return $rs;
}
public function doSelect($sql)
{
$result = $this->pdo->query($sql); // , ;
if ($result) {
$rs = $result->fetchAll(PDO::FETCH_ASSOC);
}
return $rs;
}
}
経験を総括する.
1.PDOの一般的な方法: