【发布时间】:2016-01-09 03:50:51
【问题描述】:
我有一个 DB 连接类,一切都很好,除了绑定值的步骤,它在所有字段中插入最后一个字段数据加上类型,而绑定返回数字 2 而不是(INT,BOOL,NULL,.. .) 正如我指定的那样:
所以,它应该插入:
将 fied1 倒入 field1 将 fied2 倒入 field2 将 fied3 倒入 field3
等等,下面是代码:
<?php
final class crud {
public function __construct($connexionName) {
$this->connexionName = $connexionName;
}
public final function insert($tableName, $fields=array()){
$this->tableName = $tableName;
$this->fields = $fields;
foreach ($this->fields as $vf) {
$inKeys[] = $vf;
$inKeysDotted[] = ':' . $vf;
$insImKeys = implode(', ', $inKeys);
$insImKeysDotted = implode(', ', $inKeysDotted);
$this->insImKeys = $insImKeys;
$this->insImKeysDotted = $insImKeysDotted;
}
$this->insertedKeys = $inKeys;
$this->insertedKeysDotted = $inKeysDotted;
//print_r($this->insertedKeys);
//echo '<br />';
$sql = "INSERT INTO `$this->tableName` ($this->insImKeys) VALUES ($this->insImKeysDotted);";
//echo $sql.'<br />';
$insertItems = $this->connexionName->prepare($sql);
$this->insertItems = $insertItems;
//print_r($insertItems).'<br />';
} // end prepareStm()
public final function bindParams($setValues=array()){
$combine = array_combine($this->insertedKeys, $setValues);
foreach ($combine as $getKey => $getVal) {
switch ($getVal) {
case is_int($getVal):
//echo $getVal .' is INT<br />';
$setType = PDO::PARAM_INT;
//return PDO::PARAM_INT;
break;
case is_bool($getVal):
//echo $getVal .' is BOOL<br />';
$setType = PDO::PARAM_BOOL;
//return PDO::PARAM_BOOL;
break;
case is_null($getVal):
//echo $getVal .' is NULL<br />';
$setType = PDO::PARAM_NULL;
//return PDO::PARAM_NULL;
break;
default:
//echo $getVal .' is STR<br />';
$setType = PDO::PARAM_STR;
//return PDO::PARAM_STR;
break;
return $setType;
}
echo "this->insertItems->bindParam($getKey, $getVal, $setType)<br />";
$this->insertItems->bindParam($getKey, $getVal, $setType);
//echo '<pre>';
//print_r($this->insertItems);
//echo '</pre>';
}
} // end bindParams()
public final function executeQuery(){
return $this->insertItems->execute();
}
}
require_once '../Included_Files/Connect.php';
$con = new crud($connexion);
echo '<br />';
$con->insert('test', array('field1', 'field2', 'field3'));
$con->bindParams(array('pour field1', 'pour field2', 'pour field3'));
$con->executeQuery();
?>
echo 和 print_r 的结果是:
INSERT INTO `test` (field1, field2, field3) VALUES (:field1, :field2, :field3);
this->insertItems->bindParam(field1, pour field1, 2)
this->insertItems->bindParam(field2, pour field2, 2)
this->insertItems->bindParam(field3, pour field3, 2)
感谢您的支持
【问题讨论】: