Doctrine - conditional where - php

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;
}

Related

Codeigniter Select and Count MySQL Records

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;
}

Codeigniter: query returns values of NULL

Hi there I am trying to check if my query is successful but it is returning indexes of NULL values making it seem that the query is successful. How can I check if the query is success in my sample query because I think it shouldn't return NULL indexes.
Model
public function classmanage_classinfo($section_id) {
$query = $this->db->select('students.user_id, students.studentnumber,
students.lastname, students.firstname, students.middlename, students.level, students.year')->from('sections')
->join('student_section', 'student_section.section_id = sections.section_id', 'left')
->join('students', 'students.user_id = student_section.student_id', 'left')
->where('sections.section_id', $section_id)
->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Controller
$data['class_info'] = $this->staff_model->classmanage_classinfo($section_id);
View
<p><?php var_dump($class_info) ?></p>
According to my var_dump the array is counted as a row even though the indexes are null? Why is this happening. How could I make sure that if the query isn't successful it triggers false in my if statement. If there are ways to improve or solve this logic it would be most welcome. Thanks.
Edit:
Full controller
$data['class_info'] = $this->staff_model->classmanage_classinfo($section_id);//determinant if query is null is in the model
$data['section_info'] = $this->staff_model->classmanage_sectioninfo($section_id);
Full Model
public function classmanage_classinfo($section_id) {
$query = $this->db->select('students.user_id, students.studentnumber,
students.lastname, students.firstname, students.middlename, students.level, students.year')->from('sections')
->join('student_section', 'student_section.section_id = sections.section_id', 'left')
->join('students', 'students.user_id = student_section.student_id', 'left')
->where('sections.section_id', $section_id)
->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
public function classmanage_sectioninfo($section_id) {
//section_name
$query = $this->db->select('section_name')->where('section_id', $section_id)->get('sections');
return $query->row();
}
I assume that your query returns many rows not a single row.
$query = $this->db->select('students.user_id, students.studentnumber,
students.lastname, students.firstname, students.middlename, students.level, students.year')->from('sections')
->join('student_section', 'student_section.section_id = sections.section_id', 'left')
->join('students', 'students.user_id = student_section.student_id', 'left')
->where('sections.section_id', $section_id)
->get()->result();
if (!empty($query)) {
return $query->result();
} else {
return false;
}

Codeigniter order_by name not working

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;
}

Is it possible to split query builder in Laravel?

Is it possible to split queries somehow like this?
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query = $query->where('from', $dates['from']);
if ($dates['to'])
$query = $query->where('to', $dates['to']);
$query = $query->select('Active');
return $query->get()->toArray();
}
Yes, it's possibile. But don't reassign to the same variable or you risk messing it up:
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query->where('from', $dates['from']);
if ($dates['to'])
$query->where('to', $dates['to']);
$query->select('Active');
return $query->get()->toArray();
}
In Laravel 4, its necessary to assign the get method to a variable
public function scopeGetPosts($query, $this_user = NULL){
$results = DB::table('post')
->select('*')
->where('post_status','=','publish');
if( $this_user != NULL ){
$results->where('post_author','=',$this_user->user_id);
}
$data = $results->orderBy('created_at', 'desc')
->get();
if( empty( $results ) )
$data = 'no results';
return $data;
}
In Laravel Eloquent :
$query = ModelName::where('status',1);
if($userId){
$query->where('user_id',$userId);
}
if($limit){
$query->limit($limit);
}
$result = $query->get();

Making simple allowed array in PHP? (CodeIgniter)

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;
}

Categories