So I am pulling 10 records from database at the time using AJAX call.
below is my code:
public function get_next_10($offset = 0)
{
$this->db->limit(15, $offset);
$query = $this->db->get("postovi");
return $query->num_rows() > 0 ? $query->result_array() : NULL;
}
I tried putting:
$this->db->order_by("name", "asc");
but it's throwing an error.
Its Working Fine
public function get_next_10($offset = 0)
{
$this->db->limit(15, $offset);
$this->db->order_by('name', 'asc');
$query = $this->db->get("postovi");
return $query->num_rows() > 0 ? $query->result_array() : NULL;
}
Related
I have the following function in my model to filter officer records user wise. The function is working fine.
public function getOfficer()
{
$q = $this->db->order_by('last_name','ASC')->get_where('tbl_officer', array('status' => '1', 'usr' =>$this->session->userdata('id_user')));
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
Further, I want to filter officer records only for the user = 4 in the session, by p_code->8,10 and 24
The If functions as follows :
if($usr == 4)
{
$this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);
} else {
$this->datatables->where('tbl_officer.usr', $usr);
}
How can I include this If condition into my model function mentioned above ? What can be changed ? Can anyone help ?
PLease use where_in
$this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);
to
$this->datatables->where_in('tbl_officer.p_code', [8,10,24]);
Just need to change the method of query writing
public function getOfficer()
{
$usr = $this->session->userdata('id_user');
$userArray = array(8,10,24);
$this->db->select('*');
$this->db->from('tbl_officer');
if($usr == 4){
$this->db->where_in('usr',$userArray );
}else{
$this->db->where('usr',$usr);
}
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
I'm using Codeigniter active records for some time now and this is the most ridiculous error I've got.
My query is
$this->db->select('*');
$this->db->from('my_table');
$this->db->where('is_active', 1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
//return $query->result();
return $query;
} else {
return FALSE;
}
when I use$query->result(); It is empty. When I use return $query;
the result is like below,
CI_DB_pdo_result Object
(
[num_rows] => 21
[conn_id] => PDO Object
(
)
[result_id] => PDOStatement Object
(
[queryString] => SELECT * FROM my_table WHERE is_active = 1
)
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[row_data] =>
)
Count is
[num_rows] => 21
what is missing/problem here?
I have found the issue. This thing happens because my application use PDO DB Driver. Not MySQL Driver.
$db['default']['dbdriver'] = 'pdo';
So I changed my model to support that.
$sql = "SELECT * FROM my_table WHERE is_active = 1";
$stmt1 = $this->db->conn_id->prepare($sql);
$stmt1->execute();
return $stmt1->fetchAll(PDO::FETCH_ASSOC);
Now it's working fine.
I am really sorry for your time people. And thank you very much for
trying to help.
Try this
$this->db->select('*');
$this->db->from('my_table');
$this->db->where('is_active', 1);
$query = $this->db->get();
$result = $query->result_array();
if (count($result) > 0) {
return $result;
}
else{
return FALSE;
}
You're not formatting the query array. So format it.
simple add
$query = $this->db->get()->result();
in your code
$this->db->select('*');
$this->db->from('my_table');
$this->db->where('is_active', 1);
$query = $this->db->get()->result();
if ($query->num_rows() > 0) {
//return $query->result();
return $query;
} else {
return FALSE;
}
if ($query->num_rows() > 0) then return $query->result() which returns results in object format.Like this..
if ($query->num_rows() > 0) {
return $query->result();
} else {
return FALSE;
}
Then use arrow(->) operator to retrieved required values.
For more see here Codeigniter Result Formats
If u want to get result you must use row() or result() function.
$this->db->select('*');
$this->db->from('my_table');
$this->db->where('is_active', 1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
//return $query->result();
return $this->db->get()->result();
//return $query;
} else {
return FALSE;
}
$this->db->select('*');
$this->db->from('my_table');
$this->db->where('is_active', 1);
$query = $this->db->get();
$i = 0;
foreach ($query->result() as $row) {
$i++;
$data['id'] = $row->id;
$data['username'] = $row->username;
}
if ($i > 0) {
return $data;
}
I have this method in my Laravel controller :
public function getUserOrders($userId) :array{
$results = $this->_em->createQueryBuilder()
->select('Orders.orderItemCount')
->from($this->entityClass, 'Orders')
->Where("Orders.orderItemCount > '0'")
->andWhere("Orders.orderTotalPrice > '0'")
->andWhere("Orders.usersUserId = '{$userId}'")
->getQuery()->getArrayResult();
return $results;
}
I want to change this method that $userId will be optional , so last condition is not require in this situation:
public function getUserOrders($userId = NULL) :array{
$results = $this->_em->createQueryBuilder()
->select('Orders.orderItemCount')
->from($this->entityClass, 'Orders')
->Where("Orders.orderItemCount > '0'")
->andWhere("Orders.orderTotalPrice > '0'")
if (!is_null($userId))
->andWhere("Orders.usersUserId = '{$userId}'")
->getQuery()->getArrayResult();
return $results;
}
I'm trying to figure out what is the best way to achieve this. Any suggestion?
Try this
public function getUserOrders($userId = NULL) :array{
$results = $this->_em->createQueryBuilder()
->select('Orders.orderItemCount')
->from($this->entityClass, 'Orders')
->Where("Orders.orderItemCount > '0'")
->andWhere("Orders.orderTotalPrice > '0'");
if (!is_null($userId)){
$results->andWhere("Orders.usersUserId" = $userId);
}
$results->getQuery()->getArrayResult();
return $results;
}
I have some simple function to collect allowed array, but something is not ok, can somebody help me? Here is my code
public function getAllbyLink($table, $what, $url)
{
$link=mysql_real_escape_string($url);
$query = $this->db->query("SELECT * FROM ".$table." WHERE ".$what." = '{$link}' LIMIT 0 , 1");
if ($query->num_rows() > 0)
{
return $query->result();
}
else redirect('');
}
Please read something about MVC pattern, question is clearly pointed on how to write a Model.
consider using this function
public function getTable($table, $where = array(), $select = '*', $order_by = '', $limit = '', $offset = '') {
if ($order_by !== '' && $order_by != 'RANDOM') $this->db->order_by($order_by);
if ($order_by == 'RANDOM') $this->db->order_by('id', 'RANDOM');
if ($limit !== '') $this->db->limit($limit, $offset);
$this->db->select($select);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
for your purpose call the function like this:
getTable($talbe, array('what' => $link));
//returns FALSE if no data are selected,
//or returns object with data,
if you wish return array instead replace $q->result() with $q->array_result()
Please note that active record auto escapes.
After comments:
comment-1, you can simplify that function easily just delete what you do not need, for example
public function getTable2($table, $where = array(), $limit = '', $offset = '') {
if ($limit !== '') $this->db->limit($limit, $offset);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
comment-2,when there is no data use this if-else statement
if (!$my_data = getTable2('table', array('where' => $link))) {
//there is some DATA to work with
echo "<pre>";
var_dump($my_data);
echo "</pre>";
} else {
//no DATA do redirect or tell user that there is no DATA
redirect(); //redirect to default_controller
}
comment-3, no comment;
comment-4, It also allows for safer queries, since the values are escaped automatically by the system. from this source. And another SO question about active record providing exact answer you are seeking.
My understanding of your code is:
Read all rows from table
Check if linkurl is in the list
If so, return a random row for that value
Else, redirect.
In this case, try this:
public function getAllbyLink($table,$url,$what)
{
$query = $this->db->query("
SELECT *
FROM `".$table."`
WHERE `".$what."` = '".mysql_real_escape_string($linkurl)."'
ORDER BY RAND()
LIMIT 1
");
if( !$query) return redirect('');
$result = $query->result();
if( !$result) return redirect('');
return $result;
}