I am working with two classes: usuarios, preguntas.
In preguntas I store id_usuario which correspond to the id from user, ok. But sometimes I need to display more than the id, so I made a function in usuarios. php to print this info:
This is mi code for now
usuarios.php (I'm only including relevant code for this problem)
Código PHP:
function __construct($id){
$consulta = mysql_query("SELECT * FROM usuarios WHERE id = '".$id."'");
while($item = mysql_fetch_array($consulta)){
$this->id = $item['id'];
$this ->fid = $item['fid'];
$this ->usuario = $item['alias'];
$this ->password = $item['pass'];
$this ->email = $item['mail'];
$this ->fechar = $item['fechar'];
$this ->ultima = $item['ultima'];
$this ->img_src = $item['img_src'];
$this ->reputacion = $this ->fechar = $item['reputacion'];
}
}
function miniatura(){
$html_mini = "<div>$this->usuario</div>";
return $html_mini;
}
pregunta.php (i'm only including relevant code for this problem)
Código PHP:
function get_autor(){
$us = new usuario($item['id']);
return $us->miniatura();
}
function imprimir_titular(){
$html_t = '<h1 class="prg'.$this->id.'" >[ '.$this->id_eval_q.' ] '.$this->get_autor().' pregunta: '.$this->pregunta.' , '.$this->fecha.'</h1>';
return $html_t;
}
And this is the error:
Cita:
Fatal error: Call to undefined method
usuario::miniatura() in
/home/piscolab/public_html/keepyourlinks.com/recetorium/clases/pregunta.php
on line 35 No entiendo por qué no
accede al método de la clase usuarios,
aunque me deje crear el objeto usuario
:S
Details:
- Protected atributes
Any help will be wellcome
I copied you code, change content of methods and everything works
class usuario {
function __construct($id){
echo 'ok';
}
function miniatura(){
echo 'ok';
}
}
function get_autor(){
$us = new usuario($item['id']);
return $us->miniatura();
}
Show full classes because with Your code as shown in nothing wrong.
ok, this is the file where i'm calling both:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Recetorium > Preguntas - Pregunta o responde qué y cómo cocinar algo
Cargando..
and in router.php
<?php require_once('funciones.php');
if(isset($_POST['inicio'])){
// el usuario está iniciando sesion
$iniciando = new sesion_usuarios();
if($iniciando->iniciar()){
imprimir_sesion_iniciada();
}else{
imprimir_formulario_sesion();
}
}else if(isset($_POST['registro'])){
$registrando = new registro_usuarios();
if($registrando->register()){
imprimir_usuario_registrado();
}else{
imprimir_formulario_registro();
}
}else if(isset($_GET['que']) or isset($que)){
if(isset($que))
$tarea = $que;
else
$tarea = $_GET['que'];
if($tarea == 'registro'){
imprimir_formulario_registro();
}else if($tarea == 'login'){
imprimir_formulario_sesion();
}else if($tarea == 'salir'){
cerrar_sesion();
}else if($tarea == 'ultimas_preguntas'){
listar_preguntas();
}else if($tarea == 'nueva_pregunta'){
$tem = new pregunta();
$tem->imprimir_formulario;
}else if($tarea == 'ultimas_recetas'){
$tem = new pregunta();
$tem->imprimir_formulario;
}
}else if(sesion()){
echo 'Pronto prodrás: Preguntar cosas, responder cosas y evaluar ambos. Publicar tus recetas, descubrir otras, evaluarlas y ser evaluado.';
}else{
$archivo = 'bienvenida.php';
include($archivo);
imprimir_formulario_sesion();
}
?>
Related
Hello community have a query, the issue is that I have a method that consulted the database, which invokes the method assume time parametrically.
As I commented'm using the PHP framework CodeIgniter, the question is this once consulted and loaded the first list of arrays, called: $listSubPrim
I want that list of arrays, add another array that is in the list $listSubSecu, but the issue is that I notice that does not work the way I want, although the method add array_push
principal_model.php
<?php
class Principal_model extends CI_Model {
public function __construct() {
$this->load->database();
}
function obtenerPermisosNivel($icodrol, $nivelmenu) {
try{
$sql = 'SELECT ICODMAEMENU, ICODROL, VDESMAEMENU, VDESICONO, VDESIDMAEMENU, ';
$sql = $sql.'ICODPADMENU, VDESCOMAND, SIORDPRIORIDAD, ICODSUBMENU, BACTIVO ';
$sql = $sql.'FROM TABMAEMENU ';
$sql = $sql.'WHERE ICODROL = ? ';
$sql = $sql.'AND BACTIVO = ? ';
switch ($nivelmenu) {
case NIVEL_SUB_MENU_PRIMARIO:
$sql = $sql.'AND ICODPADMENU IS NULL ';
$sql = $sql.'ORDER BY ICODMAEMENU ';
break;
case NIVEL_SUB_MENU_SECUNDARIO:
$sql = $sql.'AND ICODPADMENU IS NOT NULL ';
$sql = $sql.'AND ICODSUBMENU IS NULL ';
$sql = $sql.'ORDER BY SIORDPRIORIDAD ';
break;
case NIVEL_SUB_MENU_TERCIARIO:
$sql = $sql.'AND ICODPADMENU IS NOT NULL ';
$sql = $sql.'AND ICODSUBMENU IS NOT NULL ';
$sql = $sql.'ORDER BY SIORDPRIORIDAD ';
break;
}
$query = $this->db->query($sql, array($icodrol, ESTADO_ACTIVO));
return $query->result_array();
} catch(Exception $e){
log_message('debug', $e->getMessage()); // use codeigniters built in logging library
show_error($e->getMessage()); // or echo $e->getMessage()
}
}
function obtenerPermisosMenu($icodrol) {
try{
/* Obtenemos el listado de SubMenus Primarios de toda la lista */
$listSubPrim = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_PRIMARIO);
/* Obtenemos el listado de SubMenus Secundarios de toda la lista */
$listSubSecu = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_SECUNDARIO);
/* Obtenemos el listado de SubMenu de asociado al SubMenu primario */
foreach ($listSubPrim as $pri) {
$listSubMenuItem = array();
foreach ($listSubSecu as $sec) {
if($sec['ICODPADMENU'] == $pri['ICODMAEMENU']) {
array_push($listSubMenuItem, $sec);
}
}
if (count($listSubMenuItem) > 0) {
array_push($pri, $listSubMenuItem);
}
}
/* Obtenemos el listado de SubMenus Terciarios de toda la lista */
$listSubTerc = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_TERCIARIO);
/* Obtenemos el listado de SubMenu de asociado al SubMenu secundario */
foreach ($listSubPrim as $pri) {
$listSubSecu = $pri[10];
if (is_array(listSubSecu)) {
foreach (listSubSecu as $sec) {
$listSubMenuItem = array();
foreach ($listSubTerc as $ter) {
if($sec['ICODMAEMENU'] == $ter['ICODSUBMENU']) {
array_push($listSubMenuItem, $sec);
}
}
array_push($sec, $listSubMenuItem);
}
}
}
return $listSubPrim;
} catch(Exception $e){
log_message('debug', $e->getMessage()); // use codeigniters built in logging library
show_error($e->getMessage()); // or echo $e->getMessage()
}
}
}
?>
I realize that walking back on the list: $listSubPrim
Limited position 10 of the array should be an array, so as indicated in the code.
$listSubSecu = $pri[10];
I hope you have understood my question.
Basically I want just a list of fixes, with three levels.
Thank you.
Hello I will explain more clearly the impression the first list of arrays: $listSubPrim
$listSubPrim = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_PRIMARIO);
$listSubSecu = $this->obtenerPermisosNivel($icodrol, NIVEL_SUB_MENU_SECUNDARIO);
foreach ($listSubPrim as $pri) {
log_message('debug', '-> '.$pri['ICODMAEMENU'].' - '.$pri['ICODROL'].' - '.$pri['VDESMAEMENU']);
}
I printed the results of a list of arrays, as you will notice:
DEBUG - 2015-06-10 16:43:31 --> -> 85 - 2 - Las 20 Mejores Ofertas
DEBUG - 2015-06-10 16:43:31 --> -> 86 - 2 - Ofertas Inteligentes
DEBUG - 2015-06-10 16:43:31 --> -> 87 - 2 - Descuentos Restaurantes
DEBUG - 2015-06-10 16:43:31 --> -> 88 - 2 - Categorias
I need you in that row, add the list of array: $listSubSecu, for each row that is within the array foreach.
Aya hope I understood.
Thank you.
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 />";
}
}
I want to insert 2 times but I have routes that redirects each other, I make the first Insertion and then redirijo to another path to insert again. Would have to put begin-> transanction ()
This well done ?. regards
I first made the first Insertion, in the route
$app->post("/orders/insert", function() use($app)
{
$empleado = ORM::for_table('empleado')->select('id')->where('usuario_idusuario',$_SESSION['user_id'])->find_one();
$cliente = 'proveedor';
if(!$empleado)
{
$app->flash('error','La cuenta de usuario tiene que estar asociado a un empleado registrado en la base de datos');
$app->redirect($app->urlFor('cartList'));
}
try
{
$insertOrder = ORM::for_table('pedido')->create();
$insertOrder->fechapedido = date('Y/m/d');
$insertOrder->estado = 1;
$insertOrder->empleado_id = $empleado->id;
$insertOrder->proveedor_id = $_SESSION['idproveedor'];
$insertOrder->save();
$app->redirect("/lineorder/insert/$cliente");
}
catch(PDOException $e)
{
$app->flash('error','Ha ocurrido un error en la base de datos, no se ha insertado ningún pedido'.$e->getMessage());
$app->redirect($app->urlFor('cartList'));
}
});
After I go to the route that redirect and realized:
$app->map('/lineorder/insert/:cliente', function($cliente) use($app)
{
if(!isset($_SESSION['cart-items']))
{
$app->redirect($app->urlFor('create-order'));
$app->flash('error','No tienes carritos');
}
//Si existe la variable de sesion
else
{
if(count($_SESSION['cart-items'])>0)
{
$idpedido = ORM::for_table('pedido')->count();
foreach($_SESSION['cart-items'] as $id => $cantidad)
{
$producto = ORM::for_table('producto')->select_many('id','precioVenta','precioProveedor')->where('id',$id)->find_one();
$preciounidad = ($cliente==='proveedor') ? $producto->precioProveedor : $producto->precioVenta;
$lineorder_insert = ORM::for_table('lineapedido')->create();
$lineorder_insert->pedido_idpedido = $idpedido;
$lineorder_insert->producto_idproducto =$producto->id;
$lineorder_insert->cantidad = $cantidad;
$lineorder_insert->preciounidad = $preciounidad;
$lineorder_insert->save();
//Actualizo cantidad en la table productos
$cantidad_stock =$producto->cantidad_stock;
$cantidad_stock+=$cantidad;
$update_amount = ORM::for_table('producto')->find_one($id);
$update_amount->set('cantidad_stock',$cantidad_stock);
$update_amount->save();
$app->flash('success',"pedido {$idpedido} creado correctamente");
$app->redirect($app->urlFor('orderList'));
}
}
}
})->via('GET','POST');
I need begin->transaction()
Would you be well done?
I have written a Symfony command to import some data from an API. It works but the problem is my PHP memory usage increases when I insert a big JSON in my database. And my unitOfWork increases by '2' to after each activty import.
I have already unset all my used objects, and I have read the documentation of Symfony2 when you want to do massive batch: http://www.doctrine-project.org/blog/doctrine2-batch-processing.html
But when I use $em->clear() my entity manager gives this error:
Notice: Undefined index: 000000007b56ea7100000000e366c259 in path-to-application\vendor\doctrine\lib\Doctrine\ORM\UnitOfWork.php line 2228
Here is my complete code :
/**
* #see Command
*/
protected function configure() {
$this
->setName('ks:user:runkeepersync')
->setDescription('Synchroniser les activités d\'un utilisateur runkeeper')
->setDefinition(array(
new InputArgument('access_token', InputArgument::REQUIRED, 'Access token'),
))
}
/**
* #see Command
*/
protected function execute(InputInterface $input, OutputInterface $output) {
$accessToken = $input->getArgument('access_token');
$em = $this->getContainer()->get('doctrine')->getEntityManager();
$UserHasServices = $em->getRepository('KsUserBundle:UserHasServices')->findOneByToken($accessToken);
if (!is_object($UserHasServices) ) {
echo "Impossible de trouver l'utilisateur qui possède le jeton ".$accessToken."";
}
$user = $UserHasServices->getUser();
$service = $UserHasServices->getService();
echo "avant de requérir l'api : ".memory_get_usage()."\n";
try {
$rkApi = $this->getContainer()->get('ks_user.runkeeper');
$rkApi->setAccessToken($accessToken);
$activities = $rkApi->getFitnessActivities(0,25);
$nbParPages = 25;
$nomberActivitites = $activities->size;
$aActivities = $activities->items;
$nbPages = floor ($nomberActivitites/$nbParPages);
$aEndurance = array("Running", "Cycling", "Mountain Biking", "Walking", "Hiking", "Downhill Skiing", "Cross-Country Skiing", "Snowboarding", "Skating","Wheelchair", "Rowing", "Elliptical", "Other");
$aEnduranceUnderWater = array("Swimming");
$enduranceOnEarthType = $em->getRepository('KsActivityBundle:SportType')->findOneByLabel("endurance");
if (!is_object($enduranceOnEarthType) ) {
echo "Impossible de trouver le type de sport d'endurance";
}
$enduranceUnderWaterType = $em->getRepository('KsActivityBundle:SportType')->findOneByLabel("endurance_under_water");
if (!is_object($enduranceUnderWaterType) ) {
echo "Impossible de trouver le type de sport d'endurance sous l'eau ";
}
echo "Après avoir récupéré 25 activités : ".memory_get_usage()."\n";
$a = 0;
for($i=0;$i<=$nbPages;$i++){
if($i!=0){
$activities = $rkApi->getFitnessActivities($i,25);
$aActivities = $activities->items;
}
foreach ($aActivities as $activity) {
$a = $a+1;
$codeSport = $this->formatNameSport($activity->type);
$sport = $em->getRepository('KsActivityBundle:Sport')->findOneByCodeSport($codeSport);
if (!is_object($sport) ) {
$sport = new \Ks\ActivityBundle\Entity\Sport();
$sport->setLabel($codeSport);
$sport->setCodeSport($codeSport);
$sport->setSportType($enduranceOnEarthType);
$em->persist($sport);
$em->flush();
}
$activityDetail = json_decode($rkApi->requestJSONHealthGraph($activity->uri));
if(in_array($activity->type, $aEndurance)){
$urlActivitieDetail = $activityDetail->activity;
$ActivitySessionEnduranceOnEarth = new \Ks\ActivityBundle\Entity\ActivitySessionEnduranceOnEarth($user);
isset($activity->total_distance)? $ActivitySessionEnduranceOnEarth->setDistance($activity->total_distance) : "";
isset($activity->duration)? $ActivitySessionEnduranceOnEarth->setDuration($this->secondesToTimeDuration($activity->duration)) : "";
isset($activity->start_time)? $ActivitySessionEnduranceOnEarth->setIssuedAt(new \DateTime($activity->start_time)) : "";
$ActivitySessionEnduranceOnEarth->setModifiedAt(new \DateTime('Now'));
$ActivitySessionEnduranceOnEarth->setSport($sport);
isset($activityDetail->total_calories)? $ActivitySessionEnduranceOnEarth->setCalories($activityDetail->total_calories) : "";
isset($activityDetail->climb)? $ActivitySessionEnduranceOnEarth->setElevationGain($activityDetail->climb) : "";
$maxElevation = 0;
$minElevation = 10000;
if(isset($activityDetail->path)){
foreach($activityDetail->path as $gpsPoint){
if($gpsPoint->altitude > $maxElevation){
$maxElevation = $gpsPoint->altitude;
}
if($gpsPoint->altitude < $minElevation){
$minElevation = $gpsPoint->altitude;
}
}
$ActivitySessionEnduranceOnEarth->setElevationMin($minElevation);
$ActivitySessionEnduranceOnEarth->setElevationMax($maxElevation);
}
$em->persist($ActivitySessionEnduranceOnEarth);
$em->flush();
//Pour chaque activité on a un identifiant relatif au service qu'on synchronise
$ActivityComeFromService = new \Ks\ActivityBundle\Entity\ActivityComeFromService();
$ActivityComeFromService->setActivity($ActivitySessionEnduranceOnEarth);
$ActivityComeFromService->setService($service);
$ActivityComeFromService->setIdWebsiteActivityService($activity->uri);
$ActivityComeFromService->setSourceDetailsActivity($rkApi->requestJSONHealthGraph($activity->uri));
$ActivityComeFromService->setTypeSource("JSON");
$em->persist($ActivityComeFromService);
$em->flush();
echo "Import de l'activite num ".$a." type :".$activity->type." effectue avec success \n";
unset($ActivitySessionEnduranceOnEarth);
unset($ActivityComeFromService);
echo "UnitOFWOrk -> ".$em->getUnitOfWork()->size()."\n";
}
if(in_array($activity->type, $aEnduranceUnderWater)){
$ActivitySessionEnduranceUnderWater = new \Ks\ActivityBundle\Entity\ActivitySessionEnduranceUnderWater($user);
isset($activity->total_distance)? $ActivitySessionEnduranceUnderWater->setDistance($activity->total_distance) : "";
isset($activity->duration)? $ActivitySessionEnduranceUnderWater->setDuration($this->secondesToTimeDuration($activity->duration)) : "";
isset($activity->start_time) && !empty($activity->start_time)? $ActivitySessionEnduranceUnderWater->setIssuedAt(new \DateTime($activity->start_time)) : "";
$ActivitySessionEnduranceUnderWater->setModifiedAt(new \DateTime('Now'));
$ActivitySessionEnduranceUnderWater->setSport($sport);
isset($activityDetail->total_calories)? $ActivitySessionEnduranceUnderWater->setCalories($activityDetail->total_calories) : "";
isset($activityDetail->notes)? $ActivitySessionEnduranceUnderWater->setDescription($activityDetail->notes) : "";
$em->persist($ActivitySessionEnduranceUnderWater);
$em->flush();
$ActivityComeFromService = new \Ks\ActivityBundle\Entity\ActivityComeFromService();
$ActivityComeFromService->setActivity($ActivitySessionEnduranceUnderWater);
$ActivityComeFromService->setService($service);
$ActivityComeFromService->setIdWebsiteActivityService($activity->uri);
$ActivityComeFromService->setSourceDetailsActivity($rkApi->requestJSONHealthGraph($activity->uri));
$ActivityComeFromService->setTypeSource("JSON");
$em->persist($ActivityComeFromService);
$em->flush();
echo "Import de l'activité num ".$a." type :".$activity->type." effectué avec succès\n";
unset($ActivitySessionEnduranceUnderWater);
unset($ActivityComeFromService);
}
echo "Après chaque activité : ".memory_get_usage()."\n";
unset($sport);
unset($activityDetail);
$em->clear();
}
}
} catch (\Exception $e) {
throw $e;
}
}
Thanks, #AdrienBrault. I have tested with --env=prod --no-debug, and it is true that it consumes less memory, but the memory still increase. How can I really clear the entity manager? and stabilize the memory?
Symfony logs all SQL queries in dev environment, so first you need to disable it
// disable logger
$em->getConnection()->getConfiguration()->setSQLLogger(null);
You may use event listeners on entities, it may also increase memory usage. You can disable them like so
// remove all listeners
foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
foreach ($listeners as $listener) {
$em->getEventManager()->removeEventListener($event, $listener);
}
}
Remove unset from your code, there is no need for them, as you clear entity manager every step of your loop.
// save and clear
$em->flush();
$em->getUnitOfWork()->clear();
Remember that doctrine can optimize your queries, and improve perfomance if you group queries into one flush. So the best practice would be to execute flush once over some parts of your data. For example:
// collect 100 entities and then save them
if (($i % 100) == 0) {
$em->flush();
$em->getUnitOfWork()->clear();
}
Try to reset the entity manager with:
$this->getContainer()->get('doctrine')->resetEntityManager();
and then:
$em = $this->getContainer()->get('doctrine')->getEntityManager();
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.