SQL LIKE this OR that - php

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%')";

Related

PHP: Update value start from 0 and not 1

I have a table where I drag and drop, when I drop the row I want to update order values, it works but start updating from value 0 and I want start from 1.
Example before drag and drop:
After:
My code looks like here:
public function updateOrder(Request $request)
{
$queryParams = [];
$ids = $request->ids;
//el query será definido en su totalidad de forma manual
$query = 'UPDATE projects SET `order` = CASE id ';
//agregamos cada parámetro de orden y de id al array para respetar las convenciones de PDO
foreach ($ids as $order => $id) {
$query .= 'WHEN ? THEN ? ';
$queryParams[] = (int) $id;
$queryParams[] = (int) $order;
}
//por último agregamos los ids implicados en el update
$queryParams = array_merge($queryParams, $ids);
//generamos los ? necesarios para el array de ids en el query PDO
$whereInArray = array_fill(0, count($ids), '?');
$whereInString = implode(", ", $whereInArray);
//agregamos dicho string generado al query final
$query .= "END WHERE id IN ($whereInString)";
//realizamos el update
DB::update($query, $queryParams);
}
¿What I need to update in code?
Please try $queryParams[] = (int) $order+1;

Modify an array with values from mysql table in php

I've this json call that is working fine: (just look at the $categorias array)
$query_tienda = $mysqli->query("SELECT * FROM tiendas");
$resultado_tienda = mysqli_fetch_assoc($query_tienda);
$nombre_tienda= $resultado_tienda['nombre'];
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
include("conexion_all.php");//Contiene los datos de conexion a la base de datos
$periodo=intval($_REQUEST['periodo']);
$txt_mes=array( "1"=>"Ene","2"=>"Feb","3"=>"Mar","4"=>"Abr","5"=>"May","6"=>"Jun",
"7"=>"Jul", "8"=>"Ago","9"=>"Sep","10"=>"Oct","11"=>"Nov", "12"=>"Dic"
);//Arreglo que contiene las abreviaturas de los meses del año
$categorias []= array('Mes','Name1','Name2','Name3','Name4');
for ($inicio = 1; $inicio <= 12; $inicio++) {
$mes=$txt_mes[$inicio];//Obtengo la abreviatura del mes
$tienda_1=monto('1',$inicio,$periodo);//Obtengo ingresos de la tienda
$tienda_2=monto('2',$inicio,$periodo);
$tienda_3=monto('3',$inicio,$periodo);
$tienda_4=monto('4',$inicio,$periodo);
$categorias []= array($mes,$tienda_1,$tienda_2,$tienda_3,$tienda_4);//Agrego elementos al arreglo
}
echo json_encode( ($categorias) );//Convierto el arreglo a formato json
}
And need to change that part with something like this:
$categorias = array('Mes');
while ($contador = mysqli_fetch_array($query_tienda)) {
$categorias [] = $contador['name'];
}
To achieve the same result. I've trie diferent ways with no result, like:
$categorias = array('Mes');
while($r = mysqli_fetch_array($query_tienda) {
$row = array();
$row = array($r['nombre']);
array_push($categorias,$row);
unset($row);
}
Thanks for your help.
UPDATED: Finally find a solution:
$query_tienda = $mysqli->query("SELECT nombre FROM tiendas");
$cat = "Mes";
while ($row = mysqli_fetch_array($query_tienda)){
$cat .= ','.$row['nombre'];
$row++;
}
$categorias []= explode(',', $cat);
Thanks for all!!!
Updated and solved.
$query_tienda = $mysqli->query("SELECT nombre FROM tiendas");
$cat = "Mes";
while ($row = mysqli_fetch_array($query_tienda)){
$cat .= ','.$row['nombre'];
$row++;
}
$categorias []= explode(',', $cat);

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.

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

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

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;

Categories