Why is my array (sql between date and date) is empty? - php

I'm using Codeigniter.
I want to get in my database all the dates that are between two dates
The result for my function is always an empty array.
In my DB dates are this format: 2015-10-21
My model
public function lireListeAchats($selection = "*", $date_debut, $date_fin, $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$conditions = "date_achat BETWEEN $date_debut AND $date_fin";
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
}
$date_debut and $date_fin return in this format: 2015-10-01

It's because of $date_debut AND $date_fin, those variables are strings.
Wrap them in quotes '$date_debut' AND '$date_fin'
MySQL is interpreting 2015-10-01 as 2015 minus 10 minus 01.
Use CodeIgniter's error checking:
https://ellislab.com/codeigniter/user-guide/general/errors.html

You have a typo here. It should be either return or retour. Return seems to be better than retour.
public function lireListeAchats($selection = "*", $date_debut, $date_fin, $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$conditions = "date_achat BETWEEN $date_debut AND $date_fin";
$return= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $return;

Related

Doctrine ODM memory limit reached when inserting documents

I have a little problem, I'm getting around 800 000 datas from a json and I'm trying to insert them into a MongoDB Database. But I reach memory limit (I've set it up to 8GB for testing) while doing this. I think my script isn't optimized but I can't find where. Can you guys help me ? Here is the script :
$jsonResponse = json_decode($content->response);
$datas = $jsonResponse->hits->hits;
// On crée la collection si elle n'éxiste pas
$collection = $connection->createCollection($table->getTableName(), false );
// On enregistre les données dans la collection
foreach ($datas as $data)
{
if(!empty($data) || $data)
{
$document['_id'] = $data->_id; // ID netwoof unique
$document['_updated'] = substr($data->_source->_updated, 0, -3); // Date de dernière MàJ des données
$document['_url'] = $data->_source->_url; // Start URL
// On enregistre ensuite chaque champs définis dans le dashboard
foreach ($fields as $field)
{
// On récupère le nom du champs netwoof
$containerFieldName = $field->getContainerFieldName();
// On fait correspondre notre champ db avec celui netwoof
if( isset( $data->_source->$containerFieldName ) && (!empty($data->_source->$containerFieldName) || $data->_source->$containerFieldName == 0 ) )
$document[$field->getFieldName()] = $data->_source->$containerFieldName;
/*else
$document[$field->getFieldName()] = null;*/
}
foreach ($customFields as $customField)
{
if(!empty($customField->getFieldValue()))
$document[$customField->getFieldName()] = $customField->getFieldValue();
}
// Enregistrement des données
$collection->save($document);
}
// On réinitialise la variable
unset($document);
}
Thanks all for your answer and sorry for my english.

Not separator at the last of foreach

I'm stuck; I want to not have the "-" separator on my last item! How can I do that? I know I'm supposed to use count, but I don't know how to go further.
$report = array();
$job = null; //on met la variable a zero
$i = null;
//On extrait les valeurs dans un nouveau tableau à l'aide d'une boucle :
foreach ($values_collaborateurs as $key_collab => $row_collab)//id collab prendra chaque valeur du tableau
{
//ici ne pas mettre de report[key_collab]
//exit(var_dump($values_collaborateurs));
$report[] = $row_collab; // la valeur de id collab = indice collab
//On re extrait les valeurs: boucle du table mission:
//pour chaque élément de $values_missions => id-mission
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2]." - ";// .= concatenation pr dire s'ajoute a row mission la valeur de job
// rempli le job par des valeurs
}
}
$report[$key_collab][] = $job; //$report = table qui contient chq valeur des key collab, et tout ça tu le stock ds $job
$i = null;
$job = null; //stop - remet le cycle job a zero pour recommencer a null
}
print_r("<pre>\n");
print_r($report);
print_r("<pre>\n");
printf("<br>\n");//passage a la ligne
?>
U can delete last two chars after foreach is completed using strlen...
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2]." - ";// .= concatenation pr dire s'ajoute a row mission la valeur de job
// rempli le job par des valeurs
}
}
$job = substr($job,0,strlen($job)-2);
Other solution is:
$jobs[] = $row_mission[2]; // instead of: $job .= $row_mission[2] . " - ";
and after foreach will ended:
$job = implode(" - ", $jobs);
Use count() to determine the total number of items and compare it with a counter ($current_mission) that you increment each iteration step.
Then you can append the separator only if the current item is not the last one:
$current_mission = 1;
$total_missions = count($values_missions);
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2];// .= concatenation pr dire s'ajoute a row mission la valeur de job
if ($current_mission < $total_missions) {
$job .= ' - ';
}
// rempli le job par des valeurs
}
++$current_mission;
}
An alternative is to build an array of strings and use implode().
I highly suggest to not build an array and then use implode, as it's too much overhead for both CPU and memory. If you go for substr($job,0,strlen($job)-2); you are better off with substr($job, 0, -3);, which does exactly the same.
If it's easier to read for you, you can do $job .= ' - ' . $row_mission[2]; and then substr($job, 3);.
On a side note, your code looks buggy:
You use $report[] = $row_collab;, and later $report[$key_collab][], which means you are using $reportboth as un-indexed array and associative array. That your data looks right might just be a coincidence, because if $key_collaband $row_collab have the same value, they overwrite each other.

How can I read a table with two values (Codeigniter)

I'm working with Codeigniter.
My function works, but I want to make a change and I can't figure how to do it.
My function is doing a read where "status_offre_id" = 1.
But I want it to read "status_offer_id" = 1 AND "status_offer_id" = 2
So far I tried this:
'status_offer_id' => (1 AND 2),
'status_offer_id' => 1,2,
('status_offer_id' => 1) AND ('status_offer_id' => 2),
and more
<?php
function showOffer(){
$idCompany = $_SESSION["company"]["id"];
$conditions = array(
'company_id' => $idCompany,
'status_offer_id' => 1,
);
$offer_published = $this->offer_model->lire("*", $conditions);
$data = array();
$data["offer"]=$offer_published;
$this->_layoutHaut();
$this->load->view('Company/offer_view', $data);
$this->_layoutBas();
}
?>
public function lire($selection = "*", $conditions = array(), $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
}
Try this :
$conditions = '(company_id = "' . $idCompany . '" AND status_offer_id IN (1, 2))';
Ur using CI which has active records, try to use them
$this->db->select("*")
->from($table)
->where('company_id', $company_id)
->where('status_offer_id', 1)
->or_where('status_offer_id',2)
$where = (select * from your_table where status_offer_id IN (1, 2));
$this->db->where('company_id', $company_id);
$this->db->where($where);

SQL LIKE this OR that

I'm trying to do:
(i'm working with codeignitor)
$conditions = $tri." LIKE'%".$prenomNom."%' OR LIKE'%".$nomPrenom."%'";
I also tried:
$conditions = ($tri." LIKE '%".$prenomNom."%' OR ".$tri." LIKE '%".$nomPrenom."%'");
But the OR doesn't work... my request return only $tri like $nameLastname.
When i do echo of $nameLastname and $LastnameName everything is ok.
My code
public function rechercheParAuteur($selection = "*", $recherche = "", $tri = "", $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
//$conditions = "titre LIKE '%".$recherche."%'"; //création de la condition personnalisée
$testrecherche = str_replace("'","\'", $recherche);
$rechercheArray = explode(" ", $testrecherche);
if (isset($rechercheArray[1]))
{
$nomPrenom = $rechercheArray[0]." ".$rechercheArray[1];
$prenomNom = $rechercheArray[1]." ".$rechercheArray[0];
//$conditions = $tri." LIKE'%".$prenomNom."%' OR LIKE'%".$nomPrenom."%'";
$conditions = ($tri." LIKE '%".$prenomNom."%' OR ".$tri." LIKE '%".$nomPrenom."%'");
//echo $nomPrenom; OK
//echo $prenomNom; OK
}
else
{
$resultat = $rechercheArray[0];
$conditions = $tri." LIKE '%".$resultat."%'";
}
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
You probably want to put the condition in perens.
$conditions = "($tri LIKE '%$prenomNom%' OR $tri LIKE '%$nomPrenom%')";

Find white space in string

I have the following string. I need to find the position of the last white space.
I have tried the following code:
for ($i = 410; $i < 420; $i++) {
if ($body[$i] == ' ') {
$lastCharacter = $i;
break;
}
}
But it does not return the correct white space position. It return a position in middle of a word.
Dans cette septième étape, les coureurs vont relier Montpellier et
Albi, passant au milieu des vignes de l'arrière-pays pour faire la
jonction entre les Alpes et les Pyrénées, traversant des paysages qui
font toute la saveur du Tour. Dernière étape un peu plate avant un
week-end placé sous le signe de la montagne. Des ascensions de col, la
foule amassée sur les côtés, souffrant avec leu...
$lastSpace = strrpos($string," ");
Doc: strrpos
Use strrpos : http://php.net/manual/en/function.strrpos.php
echo $pos = strrpos($mystring, " ");

Categories