MySQL request return null Controller PHP - php

I've create a table order on my code, My idea is to generate an Unique order Id per user.
On my controller I have a code with the MYSQL request, and a function to return the result (which works on other SQL requests).
So My idea is on MySQL request is to count the number of order with the same number and If result is =1 I have to generate a new order number. On my order class I have this function:
public static function getCountOrderIfExist($bdd, $order_number) {
$requete = "SELECT * FROM Order WHERE order_number='$order_number'";
$commandes = getResultatRequete($bdd, $requete);
return !empty($commandes) ? $commandes : null;
}
And I call it on my Controller:
$count = Order::getCountOrderIfExist($bdd, $order_number);
while ($count >= 1) {
$order_number= $user_role."_".$user->getUtilisateurId().rand(1,99999)."_".$user->getEntreprise()->getId().rand(1,999999);
}
And here is the code of my getResultatRequete:
function getResultatsRequete(PDO $bdd, $requete) {
$reponse_requete = $bdd->query($requete);
if ($reponse_requete != false) {
$resultat_requete = $reponse_requete->fetchAll();
return str_replace("\\", "", $resultat_requete);
} else {
printErrorInfo($bdd, $requete, true);
return array();
}
}
When I run my code on debug mode the SQL request return NULL and I don't understand why, because when I run my Request on a terminal it works well. Any idea?

From our correspondence in the comments, it seems that the problem lies in the return statement:
return !empty($commandes) ? $commandes : null;
That statement returns any found records, or null if no records are found. However, it seems that the controller expects the function to return the number of matching records (0 if none are found).
In order to return a number for you to work with, you need to instead do a count of the returned records:
return count($commandes);
This should give you the results you need.

Related

Laravel Query Builder: order by appends field

My model looks like:
protected $appends = array('status');
public function getStatusAttribute()
{
if ($this->someattribute == 1) {
$status = 'Active';
} elseif ($this->someattribute == 2) {
$status = 'Canceled';
...
} else {
$status = 'Some antoher status';
}
return $status;
}
And I want to order a collection of this models by this status attribute, is it possible?
Model::where(...)->orderBy(???)
p.s. I need exactly orderBy, not sortBy solution.
There is no way to make Eloquent do this because it only creates a SQL query. It does not have the ability to translate the PHP logic in your code into a SQL query.
A work around is to loop over the results afterwards and manually check the appends fields. Collections may be useful here.
Either you can use
Model::where(...)->orderBy('someattribute')->get();
in this case you will only get integer value in place of someattribute, or you can use DB query s follows
DB::select(DB::raw('(CASE WHEN someattribute = 1 THEN "Active" CASE WHEN someattribute = 1 THEN "Canceled" ELSE "Some antoher status" END) AS status'))
->orderBy('someattribute', 'desc');

count the not null value using where condition in codeigniter

I am writing a function to count the null column with where condition but there is a problem in this function
protected function _get_mcq_attept_count2( $mcq_id){
$this->load->model('museranswer');
return $this->museranswe>count_by(array('mcq_id'=>$mcq_id,'bookrefrence!='=>" "));
}
this function made the query
SELECT COUNT(*) AS `numrows`
FROM `user_answer`
WHERE `mcq_id` = '321'
AND `bookrefrence` != ' '
this query return the empty column value
I hope this code work for it bcz in code-igniter i always use like this .
protected function _get_mcq_attept_count2($mcq_id)
{
$this->load->model('museranswer');
$where = array('mcq_id'=>$mcq_id);
return $this->museranswe>count_by($where);
}
/******************* FOR MODEL *********************/
public function count_by($where)
{
$this->db->select('count(mcq_id) as numrows');
$this->db->from('user_answer');
$this->db->where($where);
$this->db->where('bookrefrence !=',' ');
$qry = $this->db->get();
return $qry->result_array();
}
Change your query like this array("mcq_id" => "$mcq_id", "bookrefr‌​ence IS NOT NULL" => null). Hope you will get right answer. If it does not work, share your model with us.
return $this->museranswer->count_by(array('mcq_id'=>$mcq_id,'length(bookrefrence)>2'));

Doctrine 2 - Get total when using limit via repository

I'm new to Doctrine, and I just could not find a way to get the total number of results when using limit with Criteria (via setMaxResults function) in the EntityRepository::matching method.
In my repository (not an extend of EntityRepository), I'm using the following (I know this is not the optimal code, it is used just to learn Doctrine):
public function getAll($query = null) {
if ($query instanceof Criteria) {
$users = $this->em->getRepository('App\Entities\User')->matching($query)->toArray();
} else {
$users = $this->em->getRepository('App\Entities\User')->findAll();
}
return $users;
}
Now lets say that the Criteria is defined like so:
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
$query->setMaxResults(10);
And there are actually more than 10 users that match that.
How can I get the total number of the users that match the criteria?
If you set maxResults to 10, you get 10 results ;).
Why don't you call getAll() to get all results and apply the MaxResults later?
//search for Ron's
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
//check how many Ron's your database can find
$count = $repo->getAll($query)->count();
//get the first 10 records
$query->setMaxResults(10);
$users = $repo->getAll($query);

Codeigniter dynamic pagination and where_not_in

So I have a function in my model which pulls through jobs for a paginated table but only if they have not been booked.
My first function counts the results for how many pages there are etc.
function record_count() {
$this->db->select('id');
$this->db->from('jobs');
$this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE);
return $this->db->count_all("jobs");
}
My second actually brings in the jobs.
function getPagedJobs($limit, $start){
$this->db->limit($limit, $start);
$grabPagedJobs = $this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE)->get("jobs");
if ($grabPagedJobs->num_rows() > 0) {
foreach ($grabPagedJobs->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
The problem is that the second function gets the jobs fine, and doesn't display the ones that are booked. But the first function which counts the pages still seems to count all the results, even the booked ones. Thus giving me empty pages and PHP invalid arguments on my paginated results.
I've messed around with a lot of ways, and would prefer active record if possible but I had no success with that.
Thanks,
You have a wrong statement here,
return $this->db->count_all("jobs");
count_all("jobs") will give you number of rows in jobs table.
Replace it with this -
return $this->db->count_all_results("jobs");
Read documentation - http://ellislab.com/codeigniter/user-guide/database/active_record.html
OR an alternative method for count in ci,
$this->db->select('COUNT(*) as count');
$this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE);
$query = $this->db->get('jobs');
$result = $this->db->result($query);
return $result->count;
In your implementation you are using function $this->db->count_all which counts all rows in a table.
If you want to count the number of rows in your particular query, you should use $this->db->count_all_results function. Correct implementation is:
function record_count() {
$this->db->select('id');
$this->db->from('jobs');
$this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE);
return $this->db->count_all_results("jobs");
}

Propel: newbie problems with a criteria. Trying to debug

I have this criteria propel.
public static function getPrenotazioniAttive($id_utente)
{
$c = new Criteria();
$c->add(self::USER_ID, 18793 );
$result = self::doSelect($c);
}
After that i add this:
echo $c->toString();
that shows:
Criteria: SQL (may not be complete): SELECT FROM `prenotazione` WHERE prenotazione.USER_ID=:p1 Params: prenotazione.USER_ID => 18793
Then i call the method before this way:
$prenotazioni = PrenotazionePeer::getPrenotazioniAttive($this->getUser());
var_dump($prenotazioni);
die("entro");
that creates/execute the SQL clause below.
SELECT IFNULL(SUM(prenotazione.VALUTAZIONE),0) AS somma,
COUNT(*) AS numero
FROM `prenotazione`
WHERE prenotazione.USER_ID=18793
that clause (if i go to phpmyadmin) retrives a row from the table.
My problem: var_dump($prenotazioni); just return null, any idea?
The getPrenotazioniAttive function you posted has no return clause. It should end with return $result; if you want to get the data outside the function.

Categories