我有更新功能,数据无法更改:
function editAnggota($data,$id){
$i=0;
foreach ($data as $key => $value) {
if(!is_int($value)){
$arrayValue[$i] = $key. " = '".$value."'";
}else{
$arrayValue[$i] = $key. " = ".$value;
}
$i++;
}
$nilai = implode(', ', $arrayValue);
$s = "UPDATE `anggota` SET $nilai
WHERE id = '$id'";
$sql = $this->db->prepare($s) or die(' error : '.$this->db->error);
$sql->execute();
if(!$sql){
die('Koneksi error : '.$this->db->error);
}
if($sql){
header("location: ?op=anggota");
}else{
echo "gagal";
}
}
当我开始时:
$ db = new Database();
if(isset($_POST['edit'])){
$id = $_POST['id'];
$nama = $_POST['nama'];
$jk = $_POST['jk'];
$tempat = $_POST['tempat'];
$tanggal = $_POST['tanggal'];
$formattgl = date('Y-m-d',strtotime('$tanggal'));
$pekerjaan = $_POST['pekerjaan'];
$alamat = $_POST['alamat'];
$fotonama = str_replace(' ', '-', $id.'.jpg');
$filefoto = move_uploaded_file($_FILES['foto']['tmp_name'], '../asset/img/anggota/'.$fotonama);
$data = array(
'id'=>$id,
'nama'=>$nama,
'jk'=>$jk,
'tempat'=>$tempat,
'tanggal'=> date('Y-m-d',strtotime('tanggal')),
'pekerjaan'=>$pekerjaan,
'alamat'=>$alamat,
'foto'=>$fotonama
);
$db->editAnggota($data,$_GET['id']);
}
为什么无法更新数据? 和固定数据 它看起来我做得对,无论如何都有正确的查询,为什么它们会失败?
答案 0 :(得分:0)
虽然你所做的事情可能是正确的,但我认为这可能不是你想要的:
$db->editAnggota($data,$_GET['id']);
你可能需要这个吗?
$db->editAnggota($data,$_POST['id']);
除此之外,您应该使用占位符作为变量值,因为现在您有一个SQL注入问题。如果其中一个值包含引用'
,您甚至可能会自己导致查询出现问题。
您可以执行以下操作:
$arrayValue = array();
$values = array();
foreach ($data as $key => $value) {
$arrayValue[] = "$key = :$key";
$values[":" . $key] = $value;
}
$nilai = implode(', ', $arrayValue);
$s = "UPDATE `anggota` SET $nilai
WHERE id = :idd";
$values[':idd'] = $data['id'];
$sql = $this->db->prepare($s) or die(' error : '.$this->db->error);
$sql->execute($values);