Reputation: 538
I have this function (Update) to update data in mysql table with pdo
when using this function to update one column it's working fine.
but when using it to update multiple columns , this function will add last value to all columns
you can look to problem in photo
http://postimg.org/image/z1kv5jh9j/
blew the code I use
help plz
<?php
public function query($sql, $fields = array()){
if($this->_query = $this->_pdo->prepare($sql)){
$i = 1;
if($i <= count($fields)){
foreach ($fields as $param){
$this->_query->bindParam($i, $param);
$i++;
}
}
//die($sql);
if($this->_query->execute()){
return $this->_query;
}
}
}
public function Update($tbl_name, $fields = array(),$id){
$set = '';
$x = 1;
$bindvalues = array_values($fields);
foreach ($fields as $columns => $values) {
$set .= "`{$columns}` =?";
if ($x < count($fields)){
$set .= ", ";
}
$x++;
}
$id = intval($id);
$sql = "UPDATE `{$tbl_name}` SET {$set} WHERE `id`={$id} ";
//die($sql);
if($this->query($sql,$fields) == true){
echo "Data updated Successfully";
}
}
?>
Upvotes: 0
Views: 345
Reputation:
You need to use bindValue()
instead of bindParam()
because bindParam()
is passed to PDO byref. This makes it always use the last value set in $param
variable.
public function query($sql, $fields = array()){
if($this->_query = $this->_pdo->prepare($sql)){
$i = 1;
if($i <= count($fields)){
foreach ($fields as $param){
$this->_query->bindValue($i, $param);
$i++;
}
}
//die($sql);
if($this->_query->execute()){
return $this->_query;
}
}
}
Upvotes: 1