如果在数据库中存在codeigniter,我想插入替换 这是我的模特
public function upload($id_akun,$data){
$query = $this->db->query("SELECT * FROM akun WHERE
id_akun = '{$data['id_akun']}' ");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
$this->db->insert('foto', $data);
}
elseif ($count == 1) {
$this->db->where('id_akun', $data['id_akun']);
$this->db->update('foto', $data);
}
我成功替换(更新)数据(如果存在)但不插入数据if(empty($ count))
有条件的($ count == 1)--->没关系 condtional(空($ count))--->问题?
答案 0 :(得分:2)
试试这个
在模型中
public function upload($id_akun,$table){
$query = $this->db->query("SELECT * FROM akun WHERE id_akun = '$id_akun' ");
$result = $query->result_array();
$count = count($result);
if (empty($count)){
$this->db->insert('foto', $table);
return 0;
}
elseif ($count == 1) {
$this->db->where('id_akun', $id_akun);
$this->db->update('foto', $table);
return 1;
}
elseif (($count >= 1) {
return 2;
}
}
在控制器中
$id_akun = 25;
$table = 'table_name';
$result = $this->model_name->upload($id_akun,$table);
switch ($result) {
case 0:
$output = 'Data Inserted'
break;
case 1:
$output = 'Record Inserted'
break;
case 2:
$output = 'Multiple Record Found'
break;
}
答案 1 :(得分:0)
你可以尝试这样..
public function upload($id_akun,$data){
$this->db->where('id_akun',$data['id_akun']);
$this->db->from('akun');
$query = $this->db->get();
$rowcount = $query->num_rows();
if ($rowcount==0) {
$this->db->insert('foto', $data);
}
else {
$this->db->where('id_akun', $data['id_akun']);
$this->db->update('foto', $data);
}
答案 2 :(得分:0)
您的问题是,您正在检查count()
的结果是否为空。这将总是评估为假。
public function upload($id_akun, $data)
{
//use active record methods, otherwise, you need to sanitize input
$this->db->select('*');
$this->db->where('id_akun', $data['id_akun']);
$query = $this->db->get('akun');
if($query->num_rows() == 0){
$this->db->update...
}else{
....
}
}
答案 3 :(得分:0)
解释
如果在抓取记录中找不到任何内容,则 result_array()函数会导致空数组。因此,当您获取记录时,它会返回空数组,并且您正在计算这个空数组,它返回零长度,该长度不等于空,因此您的条件始终保持为假。
您可以使用以下代码。
<强>代码强>
function upload($id_akun, $data) {
//use active record methods, otherwise, you need to sanitize input
$this->db->select('*');
$this->db->where('id_akun', $data['id_akun']);
$query = $this->db->get('akun');
if ($query->num_rows() == 0) {
//write your Insert query here
} elseif ($query->num_rows() > 0) {
//write your Update query here
}
}
答案 4 :(得分:0)
使用Active Record(或查询生成器很快就会调用它)有几个好处:
所以,所有时间都尝试使用活动记录。
<?php
public function upload($id_akun,$data){
$query = $this->db->select('*')->where('id_akun', $data['id_akun'])->from('akun')->get();
$count = $query->num_rows();
$result = $query->result_array();
if ($count == 0)
return $this->db->insert('foto', $data);
}
elseif ($count > 1) {
$this->db->where('id_akun', $data['id_akun']);
return $this->db->update('foto', $data);
}
}