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 />";
}
}
Related
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);
I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:
http://www.server.com/en/something/else/to/do
I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.
I use this class to change Language:
class IDIOMAS {
private $UserLng;
private $langSelected;
public $lang = array();
public function __construct($userLanguage){
$this->UserLng = $userLanguage;
}
public function userLanguage(){
switch($this->UserLng){
case "en":
$lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';
// Menu
$lang['MENU_LOGIN'] = 'Login';
$lang['MENU_SIGNUP'] = 'Sign up';
$lang['MENU_LOGOUT'] = 'Logout';
$lang['MENU_SEARCH'] = 'Search';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
$lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
$lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
$lang['SUBSCRIBE_SEND'] = 'SEND';
//LOGIN
$lang['LOGIN_TITLE'] = 'Please Login to your account';
$lang['LOGIN_USER'] = 'User';
$lang['LOGIN_PASSWORD'] = 'Password';
$lang['LOGIN_ERROR'] = '¡User and/or password invalid!';
//REGISTER
$lang['REGISTER_NAME'] = 'Please write your name';
$lang['REGISTER_LAST_NAME'] = 'Please write your last name';
$lang['REGISTER_EMAIL'] = 'Write your E-mail';
$lang['REGISTER_CITY'] = 'Enter your City name';
$lang['REGISTER_COUNTRY'] = '¿Where are you from?';
$lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
$lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';
return $lang;
break;
case "es":
$lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';
// Menu
$lang['MENU_LOGIN'] = 'Entrar';
$lang['MENU_SIGNUP'] = 'Registrarse';
$lang['MENU_LOGOUT'] = 'Salir';
$lang['MENU_SEARCH'] = 'Buscar';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
$lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
$lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
$lang['SUBSCRIBE_SEND'] = 'Enviar';
//LOGIN
$lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
$lang['LOGIN_USER'] = 'Usuario';
$lang['LOGIN_PASSWORD'] = 'Clave';
$lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';
//REGISTRO
$lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
$lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
$lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
$lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
$lang['REGISTRO_PAIS'] = '¿De donde eres?';
$lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
$lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';
return $lang;
break;
}
}
}
I use this class with this code:
$language = new IDIOMAS($lang);
$langArray = array();
$langArray = $language->userLanguage();
And set the language like this:
if (!isset($_SESSION['idioma'])){
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$_SESSION['idioma'] = $lang;
}else{
$lang = $_SESSION['idioma'];
}
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
$_SESSION['idioma'] = $_GET['lang'];
$lang = $_SESSION['idioma'];
}
Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in www.server.com and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in www.server.com/es/something/else/to/do i need to change specificallly the /es parameter.
I have a function to get the current url for redirections when being logged or register.
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
I was trying to change the lang value inside that function with no success,
Really appreciate any help
Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:
// Find the first forward slash location
$pos1 = strpos($url,'/'); // The whole URL
// You only need this next line if your language codes are different sizes
// If they are always 2 then can alter the code to not use it
$pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting
$base = substr($url,0,$pos1); // Get domain name half
$end = substr($url,$pos2); // Get everything after language area
// Now from the function return the result
$val = $base.'/'.$newlang.'/'.$end;
return $val;
You may need to add or subtract 1 on the $pos to get the right values returned, like so:
$pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
$base = substr($url,0,$pos1-1); // In case its returning the slash
$end = substr($url,$pos2+1); // In case its return the slash
Please tweak and test this, it is only the concept in action, I have not tested this snip-it.
Finally i got it by modifying the getUrl function to this:
function getUrl($newlang) {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
$substr = substr($url,27,3);
$base = substr($url,0,28);
$resto = substr($url,31,1000);
$newUrl = $base.$newlang."/".$resto;
return $newUrl;
}
and calling the function like this getUrl("en") or getUrl("es");
Maybe this can be usefull for someone else.
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.
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...
I have this form that is for a hotel website. I need to validate the number of people in a room. The user selects the number of rooms and the number of people in each room. I am looping through the rooms and validating each of them has no more than 4 people, including adults and child.
I have everything pretty much done, but the class I am using seems to not be working on the loop. This is what happens; if the last room on the the list is ok with the number of people the class will allow it to record the data on the database and continue to the next step. However, it will still show the error message that no more than 4 people is allowed in the room. What it should do is go back to the last form and show the error, letting the user select the room again.
This is the code so you might help me with that:
foreach ($_POST['adt'] as $key => $adt){
$chd = $_POST['chd'][$key];
$v = new validacao;
echo $v->validarApt($chd, $adt);
echo $v->validarQpt($qpl);
echo $v->validarTpl($tpl);
echo $v->validarChd($chdroom);
echo $v->validarAdt($adt);
}
if ($v->verifica()) {
After this, if validated it should record on the database and continue with the code.
This is the class:
<?
class validacao {
var $campo;
var $valor;
var $msg = array();
function mensagens($num, $campo, $max, $min) {
$this->msg[0] = "<img src='imagens/x.jpg' /> Os apartamentos neste hotel permitem a acomodação de no máximo 4 passageiros, incluindo adultos e crianças <br />"; // apartamentos
$this->msg[1] = "<img src='imagens/x.jpg' /> Este hotel não possui apartamentos quádruplos, por favor selecione 2 apartamentos duplos <br />"; // apartamentos
$this->msg[2] = "<img src='imagens/x.jpg' /> Este hotel não possui apartamentos triplos, por favor selecione 2 apartamentos, 1 duplo e 1 single ou faça nova busca e procure por hotéis com apartamentos triplos que tenham preços divulgados em nossa tabela <br />"; // apartamentos
$this->msg[3] = "<img src='imagens/x.jpg' /> Este roteiro não dispõe de preços diferenciados para crianças, por favor inclua a criança como adulto <br />"; // apartamentos
$this->msg[4] = "<img src='imagens/x.jpg' /> Você deve incluir pelo menos 1 adulto no apartamento <br />"; // apartamentos
return $this->msg[$num];
}
function validarApt($adt,$chd) {
if ($chd + $adt >= 5) {
return $this->mensagens(0, null, null, null);
}
}
function validarQpt($qpl) {
if ($qpl == 0) {
return $this->mensagens(1, null, null, null);
}
}
function validarTpl($tpl) {
if ($tpl == 0) {
return $this->mensagens(2, null, null, null);
}
}
function validarChd($chdroom) {
if ($chdroom == 0) {
return $this->mensagens(3, null, null, null);
}
}
function validarAdt($adt) {
if ($adt == 0) {
return $this->mensagens(4, null, null, null);
}
}
function verifica() {
if (sizeof($this->msg) == 0) {
return true;
} else {
return false;
}
}
}
?>
I appreciate your help. Thanks!
This should help. You need to add a flag that will be false if any pass through the loop fails, and check that after you're done. You're only checking whether the last pass failed.
$verified = true;
foreach ($_POST['adt'] as $key => $adt){
$chd = $_POST['chd'][$key];
$v = new validacao;
echo $v->validarApt($chd, $adt);
echo $v->validarQpt($qpl);
echo $v->validarTpl($tpl);
echo $v->validarChd($chdroom);
echo $v->validarAdt($adt);
if(!$v->verifica()){ $verified = false; }
}
if ($verified) {
... //proceed with rest of code
}
You also have a problem here: (I elide some details for clarity)
class validacao {
...
var $msg = array();
function mensagens($num, $campo, $max, $min) {
$this->msg[0] = "<img src='imagens/x.jpg' /> Os apartamentos neste hotel permitem a acomodação de no máximo 4 passageiros, incluindo adultos e crianças <br />"; // apartamentos
$this->msg[1] = "<img src='imagens/x.jpg' /> Este hotel não possui apartamentos quádruplos, por favor selecione 2 apartamentos duplos <br />"; // apartamentos
...
return $this->msg[$num];
}
...
function verifica() {
if (sizeof($this->msg) == 0) {
return true;
} else {
return false;
}
}
}
The latter function will ALWAYS return false, because the former function sets a bunch of error messages. Each of your validation functions are returning the result of the mensagens function, which is always to return the member variable of the class. You should probably read up on static functions and consider what functions here should be static, which dynamic, and how you store the messages you want to return, and how that differs from the validations that actually fail.