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

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

Related

How to upload data more than once using Laravel

I'm trying to make a system where an admin creates a project template, and then templates for both text (limit on characters) and images (height/width and file extension)
When I have one template, the code works perfectly and I can even upload multiple texts/images with just one template.
But the problem comes when I create a 2nd text/image template, the template by itself is created without a problem, but when I want to upload something using that template, well...
With the problem being in this part of the code:
Here are the full codes:
Creation of the templates:
Textos_DescripcionController.php (controller of the text template) :
public function store(Request $request){
$request->validate([
'nombre_texto' => ['required'],
'min' => ['required'],
'max' => ['required'],
]);
Textos_Descripcion::create($request->all());
$data_txt = DB::table('textos__descripcions')
->max('id');
$data_proyecto = $_POST['proyecto_id'];
//dd($data_proyecto);
Textos_Descripcion_Plantillas::insert(['proyecto_id' => $data_proyecto, 'texto_descripcion_id' => $data_txt]);
return redirect('/profile/' . auth()->user()->id);
}
TextosController.php (texts by themselves):
public function store(Request $request){
$plantilla_id = $_POST['id_descr'];
//Obtenemos ancho y alto de la plantilla
$min = DB::table('textos__descripcions')
->select('min')
->where('id' , '=', $plantilla_id)
->first();
$min_valor = $min->min;
$max = DB::table('textos__descripcions')
->select('max')
->where('id' , '=', $plantilla_id)
->first();
$max_valor = $max->max;
//ahora obtenemos los ancho y alto de la imagen
$largo = strlen($_POST["texto"]);
//ahora comparamos
if($min_valor > $largo || $max_valor < $largo){
echo "El texto no cumple con los estandares, la imagen debe ser desde " . $min->min . " hasta " . $max->max . "y tu texto tiene " . $largo . " caracteres ";
dd($largo);
return redirect('/profile/' . auth()->user()->id);
};
$paro = "Aqui toy";
echo "Succes, La imagen cumple con los estandares, la imagen debe ser desde " . $min->min . " hasta " . $max->max . "y tu texto tiene " . $largo . " caracteres ";
$request->validate([
'caption' => ['required'],
'texto' => ['required'],
'id_descr' => ['required'],
]);
//dd($paro);
Textos::create($request->all()); //
//Datos a tabla intermedia
$data_img = DB::table('textos__descripcion__plantillas')
->select('id')
->where('id' ,'=', $plantilla_id)
->first();
$data_img_valor = $data_img->id;
$id_proyecto = DB::table('proyectos')
->select('id')
->where('id','=', $data_img_valor)
->first();
$id_proyecto_valor = $id_proyecto->id; //I'm getting problems here
$id_txt = DB::table('textos')
->max('id');
Textos_Proyectos::insert(['proyectos_id' => $id_proyecto_valor , 'textos_id' => $id_txt]);
return redirect('/profile/' . auth()->user()->id);
}
I used a dd() right before the line of code that gives me problems, which gave a null. And to me this doesn't make sense, because it works with the 1st template, when I use the dd() I get the id of what I'm uploading:
Why is this happening?
I apologize is the question is too vague, if it lacks details please point it out
EDIT: I decided to change the first() to get() in the line that's throwing me problems, and I got an empty array

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

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;

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

Categories