【发布时间】:2021-03-28 10:07:40
【问题描述】:
我查看了关于 SO 提出的所有其他问题,但未能在我的代码中找到问题。我正在尝试使用 Update() 方法更新数据库。我的 Insert() 方法已启动并正在运行,但在运行代码时收到上述错误。绑定我的值时似乎是一个错误。有人能给我一些建议吗?谢谢。
<?php
class DB{
private static $_instance = null;
private $_pdo,$_query,$_error = false, $_result, $_count = 0, $_lastInsertID = null;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.DB_HOST.';port=3307;dbname='.DB_NAME , DB_USER, DB_PASSWORD);
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = []){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
//binds paramaters
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()){
$this->_result = $this->_query->fetchALL(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastInsertID = $this->_pdo->lastInsertId();
} else{
$this->error = true;
}
}
return $this;
}
public function insert($table,$fields=[]){
$fieldString = '';
$valueString = '';
$values = [];
foreach( $fields as $field => $value){
$fieldString .= '`'. $field . '`,';
$valueString .= '?,';
$values[] = $value;
}
$fieldString = rtrim($fieldString, ',');
$valueString = rtrim($valueString, ',');
$sql = "INSERT INTO {$table} ({$fieldString}) VALUES ({$valueString})";
if(!$this->query($sql, $values)->error()){
return true;
}else{
return false;
}
}
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
public function error(){
return $this->_error;
}
}
?>
<?php
class Home extends Controller{
public function __construct($controller,$action){
parent::__construct($controller, $action);
}
public function indexAction(){
//die('welcome to the home controller this is the index action.');
$db = DB::getInstance();
$fields = [
'fname'=> 'Jared',
'email'=>'JBowser@123.com'];
//$contacts = $db->insert('contacts',$fields); This is how we insert to our DB.
$contacts = $db->update('contacts',3, $fields); // This is how we update our DB.
$this->view->render('home/index'); ///path from views directory **
}
}
【问题讨论】:
-
请不要把错误放在标题中
-
您可能想在更新函数中回显/转储您的 $sql 以及 $values,只是为了查看它们包含的内容
-
请不要在标题中添加SOLVED!当答案被接受时它就解决了
标签: php sql pdo foreach binding