Modify an array with values from mysql table in php - 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);

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;

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

Calling a php variable that is within an if

Can someone explain me why I cannot call a var that is set inside an if? And how to call it? I don't understand why this come empty.
I need the vars $workshop_manha and $workshop_tarde bring the values that comes from the DB.
CODE
$id = implode(",", $id);
$sql_consulta = mysql_query("SELECT * FROM pessoa WHERE id IN($id)")
or die (mysql_error());
$linha = mysql_fetch_array($sql_consulta);
$id = $linha['id'];
$nome = $linha['nome'];
$opcoes = $linha['opcoes'];
$opcoes2 = explode(":", $opcoes);
$opcoes3 = explode("+", $opcoes2[1]);
$opcao_congresso = $opcoes3[0]; // Option Congress
if(!empty($opcoes2[2])){
$opcoes4 = explode("+", $opcoes2[2]);
$pre_workshop_manha = $opcoes4[0]; // Workshop Morning Option
if($pre_workshop_manha == 'Paul Gilbert'){
$workshop_manha = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
}
if($pre_workshop_manha == 'Daniel Rijo'){
$workshop_manha = "Daniel Rijo: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
if($pre_workshop_manha == 'Maria Salvador'){
$workshop_manha = "Maria do Céu Salvador: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
}
if(!empty($opcoes2[3])){
$opcoes5 = explode("+", $opcoes2[3]);
$pre_workshop_tarde = $opcoes5[0]; // Worhshop Afternoon Option
if($pre_workshop_tarde == 'Donna Sudak'){
$workshop_tarde = "Donna Sudak: Quando as coisas ficam difíceis: Aplicações práticas da Terapia Comportamental Dialética";
}
if($pre_workshop_tarde == 'Philipp Kendall'){
$workshop_tarde = "Philipp Kendall: Estratégias dentro de tratamentos empiricamente baseados em evidências para jovens com ansiedade";
}
}
echo "Work manhã: ".$workshop_manha; //is coming empty :(
echo "Work tarde: ".$workshop_tarde; //is coming empty :(
That's because $workshop_manha and $workshop_tarde are not defined before the if statement.
Put this before the if statement:
$workshop_manha = '';
$workshop_tarde = '';
You can use them as an array().
Empty the values at the beginning :
$workshop_manha=array();
$workshop_tarde=array();
Than use the values as :
$workshop_manha[] = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
Display them as below :
if(!empty($workshop_manha)) {
foreach ($workshop_manha as $manha) {
echo "$manha <br />";
}
}
if(!empty($workshop_tarde)) {
foreach ($workshop_tarde as $tarde) {
echo "$tarde <br />";
}
}

Return the loop at initialization of the foreach

I want to return at the init of the loop and when the count of array is 10, I need to print it out.
I am not sure if it is possible because, the return is out of the foreach loop.
Thanks in advice.
This is my current code:
<?php
error_reporting(0);
include_once('include.php');
$link=connect_db();
//butta in un array tutti i forecast e usa print_r(array_count_values($array));
//fai un foreach che per ogni previsione fa partire una query con variabi $limit che è il parametro di ff.previsione e il LIMIT 0,$limit
$get_values = "select previsione from forecast where data='2014-05-30'";
$res_values = mysql_query($get_values,$link);
$arr_vals = array();
while( $values = mysql_fetch_assoc($res_values) ) {
array_push($arr_vals, $values['previsione']);
}
$new_array = array();
foreach ( $arr_vals as $key => $value ) {
$limit = $value;
$sel = "select min(op.cognome) as cogg,
op.nome,
op.cognome,
op.ore_giornaliere_time,
ff.ora,
ff.previsione
from
operatori op
join
turni_preconf tp on tp.tot_ore = op.ore_giornaliere
join
forecast ff on tp.inizio=ff.ora
where
ff.data='2014-05-30' and ff.previsione=$limit
group by op.cognome
order by rand()
limit 0,$limit";
$res_sel=mysql_query($sel,$link);
while( $er = mysql_fetch_array($res_sel) ) {
echo $er['nome'].' '.$er['cognome'].': '.remove_sec($er['ora']).'/'.sumatra($er['ora'], $er['ore_giornaliere_time']).'<br>';
$nomecognome = $er['nome'].$er['cognome'];
$orario = $er['ora'].'-'.sumatra($er['ora'], $er['ore_giornaliere_time']);
array_push($new_array, array($nomecognome => $orario));
//$new_array[$nomecognome] = $orario;
}
}
var_dump($new_array);
echo'<br>';
$array2 = call_user_func_array('array_merge', $new_array);
echo count($array2);
if(count($array2) == 10){
var_dump($array2);
}
if(count($array2) != 10){
//RETURN FROM ??? HELP...
}
//butta nome cognome ora_inizio/ora_fine nel seguente modo [nomecognome]=>"ora_inizio-ora_fine" e rimuovi le chiavi duplicate preservando l'ordine
?>
Im still not realy sure what you mean, but it sounds like (for me) that you try to print out the array after it has exactly a length of 10. Else you want to run the foreach loop again until there are 10 elements in the array?
If this is what you mean then i would consider to put your foreach in a do{}while() loop.
Similar to this one:
Edit: [UNTESTED not sure if it works properly]
<?php
//some code
do{
//code that should repeat until arraylength == 10 goes in here
foreach(...)
.
.
.
}while( count($array2) == 10 );
//no need for a second if statment,
//cause it only gets executet if we get out of the loop.
var_dump($array2);
//some other code that gets executed
.
.
.
?>
And now on your code:
<?php
error_reporting(0);
include_once('include.php');
$link=connect_db();
//butta in un array tutti i forecast e usa print_r(array_count_values($array));
//fai un foreach che per ogni previsione fa partire una query con variabi $limit che è il parametro di ff.previsione e il LIMIT 0,$limit
$get_values = "select previsione from forecast where data='2014-05-30'";
$res_values = mysql_query($get_values,$link);
$arr_vals = array();
while( $values = mysql_fetch_assoc($res_values) ) {
array_push($arr_vals, $values['previsione']);
}
// START REPEAT until count($array2) == 10
do{
$new_array = array();
foreach ( $arr_vals as $key => $value ) {
$limit = $value;
$sel = "select min(op.cognome) as cogg,
op.nome,
op.cognome,
op.ore_giornaliere_time,
ff.ora,
ff.previsione
from
operatori op
join
turni_preconf tp on tp.tot_ore = op.ore_giornaliere
join
forecast ff on tp.inizio=ff.ora
where
ff.data='2014-05-30' and ff.previsione=$limit
group by op.cognome
order by rand()
limit 0,$limit";
$res_sel = mysql_query($sel,$link);
while( $er = mysql_fetch_array($res_sel) ) {
echo $er['nome'].' '.$er['cognome'].': '.remove_sec($er['ora']).'/'.sumatra($er['ora'], $er['ore_giornaliere_time']).'<br>';
$nomecognome = $er['nome'].$er['cognome'];
$orario = $er['ora'].'-'.sumatra($er['ora'], $er['ore_giornaliere_time']);
array_push($new_array, array($nomecognome => $orario));
//$new_array[$nomecognome] = $orario;
}
}
var_dump($new_array);
echo'<br>';
$array2 = call_user_func_array('array_merge', $new_array);
echo count($array2);
}while(count($array2) != 10) //END OF REPEAT
var_dump($array2);
//butta nome cognome ora_inizio/ora_fine nel seguente modo [nomecognome]=>"ora_inizio-ora_fine" e rimuovi le chiavi duplicate preservando l'ordine
?>
Hope this helps.

Query in MySql from PHP, and JSON response for Highcharts

I have a issue whith a query on MySql table. I need a JSON response like this:
[{"data":[[1498902400000,1],[1400112000000,0],[1400112000000,0],...],"name":"1"},
{"data":[[1598902400000,0],[1500112000000,1],[1500112000000,0],...],"name":"2"},
{"data":[[1698902400000,0],[1600112000000,1],[1600112000000,1],...],"name":"3"}]
...but i recibe like this (all dates/int on "data:" identics):
[{"data":[[1498902400000,1],[1400112000000,0],[1400112000000,0],...],"name":"1"},
{"data":[[1498902400000,1],[1400112000000,0],[1400112000000,0],...],"name":"2"},
{"data":[[1498902400000,1],[1400112000000,0],[1400112000000,0],...],"name":"3"}]
...but only recibe the same "data:" (dates, int) for all names. I thing i have a malformed JSON estructure.
Thank you for help!
PHP File:
header('Content-type: application/json');
require_once('Connections/conexion.php');
///recupero nombre de Usuario de la sesion, fecha y idGrupo
$sesionUser = $_SESSION['MM_Username'];
$sesionIdGrupo = $_GET['idGrupo'];
$sesionFechaActual = $_GET['fechaActual'];
///ARREGLO FECHA RECIBIDA PARA ADAPTARLA A FORMATO DE LA BD YY-MM-DD
$SesionFechaActualMes = explode("-", $sesionFechaActual);
mysql_select_db($database_conexion, $conexion);
$contador=1;
$arr = array();
$items2 = array();
$dia=1;
do {
$idDispositivoWhile = $row_RecordsetTabla3['idDispositivo'];
while ($dia < 31) {
$query_RecordsetTabla = "SELECT fecha, count(estado) FROM registros WHERE estado = '2' AND idUsuario = 'xavi' AND idGrupo = '393' AND YEAR(fecha) = '$SesionFechaActualMes[1]' AND MONTH(fecha) = '$SesionFechaActualMes[0]' AND DAY(fecha) = '$dia' AND idDispositivo='$contador'";
$RecordsetTabla = mysql_query($query_RecordsetTabla, $conexion) or die(mysql_error());
$row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla);
$totalRows_RecordsetTabla = mysql_num_rows($RecordsetTabla);
$fecha = $row_RecordsetTabla['fecha'];
$estadoCount = $row_RecordsetTabla['count(estado)'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloFecha2 = strtotime($arregloFecha) * 1000;
$contador++;
$arr = array($arregloFecha2, floatval($estadoCount));
$items['data'][] = $arr;
}/////while que busca 31 fechas
$items['name'] = $contador;
array_push($items2, $items);
} while ($contador < 3); /////while contador hasta 3
echo json_encode($items2);
////mysqlfreeresult
mysql_free_result($RecordsetTabla);
Note: The results is for fill a Highcharts chart.
Thanks!!!
I put a screen capture of table in Mysql...

Categories