I want to insert of replace if exist in database with codeigniter
this my model
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);
}
I'm succesful replace(update) data if exist but it not inserting data if (empty($count))
conditional ($count == 1)---> it's ok
condtional (empty($count))--->problem?
Try this
In Model
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;
}
}
In Controller
$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;
}
You can try like this ..
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);
}
Your problem is you're checking to see if the result of a count() is empty. That will always evaluate to false.
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{
....
}
}
Explanation
The function result_array() results empty array if nothing is find in fetching record. Hence when you fetch record it returns you the empty array and you are taking count of this empty array which returns you the zero length which is not equals to empty hence your condition is always remain false.
You may use the following Code.
Code
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
}
}
There are several benefits to using Active Record (or Query Builder as its going to be called soon):
Security
Code-Cleanliness
Database-Agnostic
so, all time try to use 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);
}
}
Related
I want to build a query nested in codeigniter
here is the my controller
public function advancedSearch(){
if (!$this->session->userdata('logged_in')) {
redirect('main/login', 'refresh');
}
$session_data = $this->session->userdata('logged_in');
$data['code'] = $session_data['code'];
$start = $this->input->post('start');
$end =$this->input->post('end');
$ticket = $this->input->post('ticket');
$type =$this->input->post('type');
$this->db->select('*');
$this->db->from('table');
if ($start && $end) {
$this->db->where('date >=',$start);
$this->db->where('date <=',$end);
} else if ($ticket) {
$this->db->where('ticket','yes');
} else if ($type) {
$this->db->where('type',$type);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
$data['data'] = $query->result();
}
//print_r($data);
$this->load->view('advanced-search',$data);
with this code I just get the first input a click and search, If I click just ticket I get the $this->db->where('ticket','yes'); I hope I explained well.
Greetings
Hope this will help you :
instead of using if else use it with only if with empty check
if ( ! empty($start))
{
$this->db->where('date >=',$start);
}
if (! empty($end))
{
$this->db->where('date <=',$end);
}
if (! empty($ticket))
{
$this->db->where('ticket','yes');
}
if (! empty($type))
{
$this->db->where('type',$type);
}
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['data'] = $query->result();
}
//print_r($data);
$this->load->view('advanced-search',$data);
Controller[In Article Page Article Properly work with pagination, store user email id in 'articles' database , now i tried to get the user firstname, and lastname from users table but not work properly ]
public function articles()
{
$data['title'] = "Articles";
$config = array();
$config["base_url"] = base_url() . "sd/articles/";
$config["total_rows"] = $this->model_users->record_count_articles();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model_users->fetch_result_articles($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
if ($this->session->userdata ('is_logged_in')){
$data['profile']=$this->model_users->profilefetch();
$this->load->view('sd/header',$data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/footer', $data);
} else {
$this->load->view('sd/sdheader', $data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/sdfooter', $data);
}
}
Model [ Get Users Name in Article Page ]
public function record_count_articles() {
return $this->db->where('status','1')->count_all("articles");
}
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->where('status','1')->order_by('id', 'DESC')->get("articles");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Add These Lines [ But Not Work]
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
$query = $this->db->select('firstname')->select('lastname')->where('email',$data[0]->email)->get("users");
$data['name_info']=$query->result_array();
}
return $data;
}
return false;
You have 2 problem here. please have a look on comments in code.
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//1) $data[0]->email keep repeating same email.
// inner $query variable should be different.
$innerQuery = $this->db->select('firstname,lastname')->where('email',$row->email)->get("users");
//2) you need to store query result on array.
// $data['name_info'] stores only single record.
$data[]=$innerQuery ->result_array();
}
return $data;
}
return false;
You should avoid query in loop if you can achieve it by join
EDIT: Lets try this with join
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db
->join('users u','u.email = a.email','left')
->where('a.status','1')->order_by('a.id', 'DESC')->get("articles a");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I have not tested the code. but it is better way than loop.
I am trying to loop a function through while similar to WordPress. I use the function to return a boolean of true or false. Now here is my function. Now, with it only returning true or false, I know that I have to get my function has_rows(); to change to false after it looks through all my rows. Is this possible?
So I guess my question is if it is possible, and how, to loop the a function in a while loop like the below example. I know it is possible because wordpress uses a function, my question is how.
THIS is what I have tried. And the loop wont stop.
function has_rows () {
global $Q_INFO;
global $DB_CONN;
static $COUNT; // STATIC TO REMEMBER LAST TIME FUNCTION CALLED
$COUNT = #$COUNT ? $COUNT++ : 0; // IF NOT SET, SET TO 0 AND COUNT EACH LOOP
echo $QUERY = "SELECT * FROM `" . $Q_INFO['table'] . "` LIMIT " . $COUNT . ", 1";
$STMT = $DB_CONN->prepare($QUERY);
$STMT->execute();
$RESULT = $STMT->get_result();
$STMT->close();
if ($RESULT->num_rows > 0) {
return true;
} else {
return false;
}
}
Im calling it just like in wordpress:
<?php if (has_rows()):?>
<?php while (has_rows()): ?>
Hi World!!
<?php endwhile; ?>
<?php endif; ?>
HERE IS MY FINAL CODE:
I had to add another static variable for the very first call of the function in if(has_rows()): and then I used the selected answer below to do the rest.
Thanks for the help guys!
function has_rows () {
global $Q_INFO;
global $DB_CONN;
static $I = 0;
static $COUNT = 0;
if ($I == 0) {
$QUERY = "SELECT * FROM `" . $Q_INFO['table'] . "`";
$I++;
} else {
$QUERY = "SELECT * FROM `" . $Q_INFO['table'] . "` LIMIT " . $COUNT . ", 1";
$COUNT++;
}
$STMT = $DB_CONN->prepare($QUERY);
$STMT->execute();
$RESULT = $STMT->get_result();
$STMT->close();
if ($I != 0) {
while ($ROW = $RESULT->fetch_assoc()) {
foreach ($ROW as $KEY=>$VALUE) {
$Q_INFO[$KEY] = $VALUE;
}
}
}
if ($RESULT->num_rows > 0) {
return true;
} else {
return false;
}
}
The first time you run it, $COUNT is 0, which evaluates to boolean false. So, $COUNT = #$COUNT ? $COUNT++ : 0; sets it to 0 again.
Just take out that line, explicitly initialize $COUNT to 0, and put $COUNT++; right before your final if statement.
function has_rows () {
global $Q_INFO;
global $DB_CONN;
static $COUNT = 0; // STATIC TO REMEMBER LAST TIME FUNCTION CALLED
// Other code here...
$COUNT++;
if ($RESULT->num_rows > 0) {
return true;
} else {
return false;
}
}
If your trying just to walk over an array, like the wordpress does, try this:
$posts = array('post1', 'post2', 'post3');
function has_posts()
{
// this line will make sure that you have a non empty array
if ( ! is_array($posts) or ! count($posts)) return false;
else return each($posts);
}
while ($post = has_posts())
{
echo $post;
}
I have to store into MySQL from PHP quite a lot; usually the content to be stored I have in arrays. So I have written a small set of helper functions that saved me a lot of time.
This is the main function store that stores $array into MySQL $table:
function store($array, $table, $limit = 1000, $mode = '') {
if (empty($array)) return FALSE;
$sql_insert = "INSERT INTO `".$table."` (";
$array_keys = array_keys($array);
$keys = array_keys($array[$array_keys[0]]);
foreach ($keys as $key) $sql_insert .= "`".$key."`,";
$sql_insert = replaceEND($sql_insert, ') VALUES ', 1);
$count = 1;
$sql = $sql_insert;
foreach ($array as $array_num => $row) {
$sql .= '(';
foreach ($row as $key => $value) {
$string = $value;
if (!is_null($value)) {
$sql .= "'".str_replace("'", "\'", $string)."',";
} else {
$sql .= "NULL,";
}
}
$sql = replaceEND($sql, '),', 1);
$count = checkInsert($sql, $count, $limit);
if ($count == 0) {
if ($mode == 'PRINT') echo $sql.'<br />';
$sql = $sql_insert;
}
$count++;
}
$last = lastInsert($sql);
if ($last) {
if ($mode == 'PRINT') echo $sql.'<br />';
}
return TRUE;
}
I am using the following helpers within this function -
To add the correct ending to the statement strings:
function replaceEnd($string, $replacer = ';', $number_of_chars = 1) {
return left($string, strlen($string) - $number_of_chars) . $replacer;
}
To check, if $limit is reached which will lead to execution of the statement:
function checkInsert($sql, $sqlcount, $sql_limit) {
if ($sqlcount >= $sql_limit) {
$sql = replaceEND($sql);
query($sql);
$sqlcount = 0;
}
return $sqlcount;
}
To check for the last insert after the loop is finished:
function lastInsert($sql, $sql_insert = '') {
if (right($sql, 1) != ';') {
if ($sql != $sql_insert) {
$sql = replaceEND($sql);
query($sql);
return TRUE;
}
}
return FALSE;
}
Finally, to execute my statements:
function query($sql) {
$result = mysql_query($sql);
if ($result === FALSE) {
## Error Logging
}
return $result;
}
Basically, there is nothing wrong with these functions. But there is one problem, that I just could not solve: As you see, $limit is set to 1000 by default. This is usually perfectly fine, but when it comes to insert statements with much content / many characters per line of the insert statement, I have to reduce $limit manually in order to avoid errors. My question: does anyone know a way to automatically check if the current insert statement has reached the maximum in order to be executed correctly without wasting time by executing it too early? This would solve two problems at once: 1. I could get rid of $limit and 2. It would minimize the execution time needed to store the array into MySQL. I have just not found any approach to check the maximum possible length of a string that represents a MySQL insert statement, that I could apply before executing the statement...!?
I have this function:
function gi_get_by($col,$id, $itd, $tbl, $limit = 10)
{
$this->db->select('*');
$this->db->from('global_info');
$this->db->join($tbl, 'id_' . $tbl . ' = id_global_info');
$this->db->where('info_type_id', $itd);
if($col == 'date_created' || $col == 'tag') {$this->db->like($col, $id);}
else {$this->db->where($col, $id);}
if($tbl == 'ad') :
$this->db->order_by('paid', 'desc');
endif;
$this->db->order_by('date_created', 'desc');
$this->db->limit($limit, $this->uri->segment(2));
$q = $this->db->get();
return $q = $q->result_array();
}
What I need is to count number of results before limit and to use them later in controller. I have an idea to duplicate this function without $limit but then it will be duplicating the same function. Is there another way to do this or I have to go with duplication?
I don't quite understand what you want to do but if you want an optional limit you can default it to false:
function gi_get_by($col,$id, $itd, $tbl, $limit=false)
{
$this->db->select('*');
$this->db->from('global_info');
$this->db->join($tbl, 'id_' . $tbl . ' = id_global_info');
$this->db->where('info_type_id', $itd);
if($col == 'date_created' || $col == 'tag') {$this->db->like($col, $id);}
else {$this->db->where($col, $id);}
if($tbl == 'ad') :
$this->db->order_by('paid', 'desc');
endif;
$this->db->order_by('date_created', 'desc');
if ($limit) {
$this->db->limit($limit, $this->uri->segment(2));
}
$q = $this->db->get();
return $q = $q->result_array();
}
This will conditionally add limit clause if it is passed in to the function.
Also it would be best to pass in wwhatever $this->uri->segment(2) into the function as a parameter instead of accessing it from within the function.
Why not select
sql_calc_found_rows
in your query?
http://www.justincarmony.com/blog/2008/07/01/mysql-php-sql_calc_found_rows-an-easy-way-to-get-the-total-number-of-rows-regardless-of-limit/
Well, how about something like this:
function gi_get_by($col,$id, $itd, $tbl, $limit = 10)
{
$count = $this->db->query('SELECT * FROM my_table')->num_rows();
//the rest stuff
}
You should use Active Record Cache:
http://codeigniter.com/user_guide/database/active_record.html#caching
function gi_get_by($col,$id, $itd, $tbl, $limit = 10)
{
// Start the cache
$this->db->start_cache();
$this->db->select('*');
$this->db->from('global_info');
$this->db->join($tbl, 'id_' . $tbl . ' = id_global_info');
$this->db->where('info_type_id', $itd);
if($col == 'date_created' || $col == 'tag') {$this->db->like($col, $id);}
else {$this->db->where($col, $id);}
if($tbl == 'ad') :
$this->db->order_by('paid', 'desc');
endif;
$this->db->order_by('date_created', 'desc');
// Stop the cache
$this->db->stop_cache();
// Get the total
$total = $this->db->count_all_results();
// Now set the limit
$this->db->limit($limit, $this->uri->segment(2));
$q = $this->db->get();
// Important! Clear the cache
$this->db->flush_cache();
return $q = $q->result_array();
}