1.添加数据
/**
* 添加我的地址
* @param array $data : cols => value
*/
function add_new_address( $data ) {
if ( empty($data) || !is_array($data) ) {
return;
}
foreach ($data as $key => $value) {
if ( $value === '') {
unset($data[$key]);
}
}
$cols = array_keys($data);
$values = array_values($data);
$cols_str = implode(',', $cols);
$values_str = implode(',', $values);
$sql = "INSERT INTO " . TBL_PRE . "member_addr ({$cols_str}) VALUES ({$values_str})";
$this->db->query($sql);
}
如要使得拼接的sql语句有效,必须在表单值两边添加单引号,int类型的字段可以不加单引号,如下所示:
if($_POST['key']=="add"){
//接受表单数据,int型的不用添加单引号
$userinfo=array(
"username"=>"'".$_POST['username']."'",
"password"=>"'".$_POST['password']."'",
"realname"=>"'".$_POST['realname']."'",
"email"=>"'".$_POST['email']."'",
"cellphone"=>"'".$_POST['cellphone']."'",
);
//调用模型类的方法将数据添加到数据表中
$this->user_model->add_new_addr($userinfo);
}
2.编辑数据
/**
* 编辑我的地址
* @param $member_id
* @param $data
*/
function edit_my_addr($addr_id, $data) {
if ( empty($data) || !is_array($data) ) {
return;
}
foreach ($data as $key => $value) {
$str .= isset($str)?", {$key} = {$value}":"{$key} = {$value}";
}
$sql = "UPDATE " . TBL_PRE . "member_addr SET {$str} WHERE addr_id = '{$addr_id}'";
$this->db->query($sql);
}
3.删除数据
/**
* 删除指定的地址
* @param $addr_id
*/
function del_this_addr( $member_id, $addr_id ) {
if ( empty($addr_id) ) {
return;
}
$sql = "DELETE FROM " . TBL_PRE . "member_addr WHERE member_id='{$member_id}' AND addr_id = '{$addr_id}'";
$this->db->query($sql);
}
4.获取数据
/**
* 获取我的所有地址
* @param int member_id
* @return array
*/
function get_my_addr( $member_id ) {
$sql = "SELECT * FROM " . TBL_PRE . "member_addr WHERE member_id = '{$member_id}' ORDER BY addr_id DESC";
return $this->db->get_all($sql);
}
5、获取拼接的sql语句:
if($_POST['key']=="add"){
//接受表单数据,int型的不用添加单引号
$userinfo=array(
"username"=>"'".$_POST['username']."'",
"password"=>"'".$_POST['password']."'",
"realname"=>"'".$_POST['realname']."'",
"email"=>"'".$_POST['email']."'",
"cellphone"=>"'".$_POST['cellphone']."'",
);
//调用模型类的方法将数据添加到数据表中
$this->user_model->add_userinfo($userinfo);
}