php loop with validate class - php

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.

Related

Get the username from a login php script

I'm using a login script that I have found in Innvo.com, they do not answer... I have modified a little bit this code though, I need to retrieve the username value at the login page and I can not find the way... first I will put the code of the file (login.php) with all the classes that take care of the login, then the code that should go in the login page (access.php), where I need to retrieve the username of the logged user... thanks
FILE: login.php
// Some pre-defined constants to indicate the login state
define('LOGIN_NOERROR',0);
define('LOGIN_USER_CREDENTIALS',-1);
define('LOGIN_USER_EXISTS',-2);
define('LOGIN_USER_NONEXISTS',-3);
define('LOGIN_PASSWORD_LINKSENT',-4);
define('LOGIN_PASSWORD_BADMATCH',-5);
define('LOGIN_PASSWORD_TOOSHORT',-6);
define('LOGIN_PASSWORD_LINKEXPIRED',-7);
define('LOGIN_SESSION_EXPIRED',-8);
define('LOGIN_AWAITS_APPROVAL',-9);
class auth {
private $db = null; // Database object
private $baseurl = 'https://exemple.com/recover.php'; // a URL that will have this script included. Used for password reset emails which require a hyperlink
private $hashfunction = 'sha256'; // Hash function used, this is always computed by PHP due to mysql versions giving binary & non-binary outputs depending on its version
private $hashlength = 32; // Length of $this->hashfunction output in binary format
private $secret = 'LDGH$$$$$'; // A secret salt used in passwords alongside user-specific salts, change this
public $account = array(); // User details on successful login
private $errors = array( // Error array for when there is a UI issue for the user
LOGIN_NOERROR=>'',
LOGIN_USER_CREDENTIALS=>'<br /><h3 style="margin-left: 20px;">Usuari i/o contrasenya incorrectes!</h3>',
LOGIN_USER_EXISTS=>'<br /><h3 style="margin-left: 20px;">Aquest usuari ja existeix al sistema!</h3>',
LOGIN_USER_NONEXISTS=>'<br /><h3 style="margin-left: 20px;">Aquest usuari no existeix al sistema!</h3>',
LOGIN_PASSWORD_LINKSENT=>'<br /><h3 style="margin-left: 20px;">Li hem enviat un correu electrònic amb un enllaç per a restablir la contrasenya. Ha de seguir les instruccions que s\'esmenten al correu per a crear una contrasenya nova.</h3>',
LOGIN_PASSWORD_BADMATCH=>'<br /><h3 style="margin-left: 20px;">Les contrasenyes no coincideixen!</h3>',
LOGIN_PASSWORD_TOOSHORT=>'<br /><h3 style="margin-left: 20px;">Les contrasenyes han de tenir al menys 8 caràcters!</h3>',
LOGIN_PASSWORD_LINKEXPIRED=>'<br /><h3 style="margin-left: 20px;">L\'enllaç per a restablir la contrasenya ha caducat!</h3>',
LOGIN_SESSION_EXPIRED=>'<br /><h3 style="margin-left: 20px;">La seva sessió ha caducat!</h3>',
LOGIN_AWAITS_APPROVAL=>'<br /><h3 style="margin-left: 20px;">El seu compte espera l\'aprovació de l\'administrador del lloc, rebrà un correu quan això estigui fet!</h3>'
);
public $forms = array( // Unique HTMLforms used
'signin'=>array(
'fields'=>array(
'username'=>array('type'=>'text','placeholder'=>'Correu electrònic','icon'=>'envelope'),
'password'=>array('type'=>'password','placeholder'=>'Contrasenya','icon'=>'lock')
),
'submit'=>'Accedir',
'message'=>'<br /><h3 style="margin-left: 20px;">Introdueixi el seu correu electrònic i la seva contrasenya per accedir-hi</h3>'
),
'signup'=>array(
'fields'=>array(
'newusername'=>array('type'=>'text','placeholder'=>'Correu electrònic','icon'=>'envelope'),
'newnamelastname'=>array('type'=>'text','placeholder'=>'Nom i cognom','icon'=>'envelope'),
'newpassword'=>array('type'=>'password','placeholder'=>'Contrasenya','icon'=>'lock'),
'confirmnewpassword'=>array('type'=>'password','placeholder'=>'Confirmi la contrasenya','icon'=>'lock')
),
'submit'=>'Crear un compte nou',
'message'=>'<br /><h3 style="margin-left: 20px;">Si us plau, empleni tots els camps per a crear el seu compte.
És important que el correu sigui vàlid per a poder recuperar la contrasenya si fos el cas!</h3>'
),
'lost'=>array(
'fields'=>array(
'lostusername'=>array('type'=>'text','placeholder'=>'Correu electrònic','icon'=>'envelope')
),
'submit'=>'Envia\'m el correu',
'message'=>'<br /><h3 style="margin-left: 20px;">Introdueixi el seu correu electrònic per a rebre les instruccions de recuperació de la seva contrasenya</h3>'
),
'reset'=>array(
'fields'=>array(
'newpassword1'=>array('type'=>'password','placeholder'=>'Contrasenya','icon'=>'lock'),
'newpassword2'=>array('type'=>'password','placeholder'=>'Confirmi la contrasenya','icon'=>'lock')
),
'submit'=>'Restableix la contrasenya',
'message'=>'Estableixi una nova contrasenya pell seu usuari!'
)
);
// Initiate the database if its not connected already
public function __construct($dbobj = null) {
!$dbobj->connect_errno
or die("Failed to connect to MySQL: (" . $dbobj->connect_errno . ") " . $dbobj->connect_error);
$this->db = &$dbobj;
if(isset($_COOKIE['cddzck']) && $this->session_validate()) {
// Logged In here
if(isset($_GET['logout']))
$this->logout();
}
else {
// Sign in attempt
if(isset($_POST['username'],$_POST['password']))
$this->login($_POST['username'],$_POST['password']);
// Sign up attempt
else if(isset($_POST['newusername'],$_POST['newnamelastname'],$_POST['newpassword'],$_POST['confirmnewpassword']))
$this->user_add($_POST['newusername'],$_POST['newnamelastname'],$_POST['newpassword'],$_POST['confirmnewpassword']);
// Lost password, email submitted via form
else if(isset($_POST['lostusername']))
$this->password_reset_form($_POST['lostusername']);
// Lost password area
else if(isset($_GET['reset']) && $this->session_valid($_GET['reset'])) {
// Form not submitted
if(!isset($_POST['newpassword1'],$_POST['newpassword2']))
$this->session_check($_GET['reset'],'lostpassword');
// Form submitted
else
$this->password_reset($_GET['reset'],$_POST['newpassword1'],$_POST['newpassword2']);
}
// Login as user, for use within an admin area to impersonate a logged in user
// You should add in the session value yourself in the admin area using $this->session_add($userid,$type = 'login') and then login via this method/URI
else if(isset($_GET['cddzck']) && $this->session_valid($_GET['cddzck'])) {
if(($this->session_check($_GET['cddzck'],'login') == 0) && isset($this->account['id'])) {
setcookie("cddzck",$_GET['cddzck'],time() + 21600);
$this->redirect();
}
else
sleep(1);
}
// None shall pass (unless logged in...)
die($this->form(LOGIN_NOERROR,(isset($_GET['form']) && in_array($_GET['form'],array('signup','lost','reset')) ? $_GET['form'] : 'signin')));
}
}
// Add a session to the hash table
public function session_add($userid,$type = 'login') {
$hash = hash($this->hashfunction,bin2hex(openssl_random_pseudo_bytes($this->hashlength)));
$result = $this->query('INSERT IGNORE sessions (hash,sessiontype,userid,created)
VALUES (UNHEX(\''.$hash.'\'),\''.$type.'\','.$userid.',UNIX_TIMESTAMP())');
return $hash;
}
// Run this in a cron job once an hour to remove stale sessions and lost password requests
public function housekeeping() {
// Remove sessions older than 6 hours
// Remove password reset authentication strings after 1 hour
$this->query('DELETE FROM sessions
WHERE (sessiontype = \'login\' AND created < UNIX_TIMESTAMP() - 21600)
OR (sessiontype = \'lostpassword\' AND created < UNIX_TIMESTAMP() - 3600);');
}
// User is not logged in, display one of the forms
private function form($error,$formname) {
// Throttle failed attempts
if($formname == 'signin' && $error != 0)
sleep(1);
// Show a sign up or sign in link in the navigation
if($formname == 'signin')
$link = '<p>Crear compte nou</p>';
else
$link = '<p>Accedir</p>';
// Get all form fields and buttons
$formfields = '';
foreach($this->forms[$formname]['fields'] as $name => $field)
$formfields .= sprintf('<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="glyphicon glyphicon-%s blue"></i></span>
<input name="%s" type="%s" placeholder="%s" class="form-control">
</div>
',$field['icon'],$name,$field['type'],$field['placeholder']);
$formfields .= sprintf('<p class="center col-md-5"><button class="btn btn-primary" type="submit">%s</button></p><p> </p>',$this->forms[$formname]['submit']);
// Navigation links for sign up/sign in/forgot password
$navigation = '<ul class="nav navbar-nav navbar-left">
<li>'.$link.'</li>
<li><p>Recuperar contrasenya</p></li>
</ul>';
// Form wrapped in bootstrap 3.0 HTML with variables inserted
$form = sprintf('<div class="well col-md-5 center login-box">
<div class="alert alert-info">%s </div>
<form method="post" action="?form=%s" class="form-horizontal">%s</form>
</div>',($error != 0 ? $this->errors[$error] : $this->forms[$formname]['message']),$formname.(isset($_GET['reset']) ? '&reset='.$_GET['reset'] : ''),$formfields);
// The above HTML is taken from a bootstrap template, you can place it into an existing template as such, using %s placeholders for the content area and navigation, for example.
// echo sprintf(file_get_contents('template.html'),$navigation,$form);
// otherwise, here is the raw output that is used
echo $navigation.'<hr>'.$form;
exit(0);
}
// User is trying to log in
private function login($username,$password) {
$result = $this->query('SELECT id,active,salt,password
FROM users
WHERE active = \'1\' AND username = \''.$this->db->real_escape_string($username).'\';');
// We fetch the row because MySQL's SHA2() functions returns either a binary of hex string format depending on version.
// For simplicity the comparison is made in PHP, though it's trivial to change this to save the roundtrip of data
if(!($this->account = $result->fetch_array(MYSQLI_ASSOC)))
die($this->form(LOGIN_USER_CREDENTIALS,'signin'));
else if($this->account['password'] != pack('H*',hash($this->hashfunction,$this->secret.$this->account['salt'].$password)))
die($this->form(LOGIN_USER_CREDENTIALS,'signin'));
// Successful login, you're about to be logged in and redirected
$this->query('UPDATE users
SET lastlogin = UNIX_TIMESTAMP()
WHERE id = '.$this->account['id']);
$hash = $this->session_add($this->account['id'],'login');
setcookie("cddzck",$hash,time() + 21600);
$this->redirect();
}
// Add a new user to the database and send the mail to awaits approval
private function user_add($username,$namelastname,$password,$password2) {
if($password != $password2) // Passwords do not match
die($this->form(LOGIN_PASSWORD_BADMATCH,'signup'));
elseif(strlen($password) < 8) // Password less than 8 characters
die($this->form(LOGIN_PASSWORD_TOOSHORT,'signup'));
$salt = openssl_random_pseudo_bytes($this->hashlength);
$hash = pack("H*",hash($this->hashfunction,$this->secret.$salt.$password));
$this->query('INSERT IGNORE users (created,username,namelastname,salt,password)
VALUES (UNIX_TIMESTAMP(),\''.$this->db->real_escape_string($username).'\',\''.$this->db->real_escape_string($namelastname).'\',\''.$this->db->real_escape_string($salt).'\',\''.$this->db->real_escape_string($hash).'\');');
if($this->db->affected_rows < 1)
die($this->form(LOGIN_USER_EXISTS,'signup'));
//ach $this->login($username,$password);
$emailcontents = sprintf("Nou usuari $username ($namelastname) esperant l'aprovació pel seu compte!");
$from = "CddZ-IAC";
$headers = "From: $from";
mail('andres#chandia.net','Nou usuari al CddZ esperant l\'aprovació!', $emailcontents, $headers, '-f ' . $from);
die($this->form(LOGIN_AWAITS_APPROVAL,'signin'));
}
// Reset a password, displays the reset password form if a valid authentication string is provided
private function password_reset_form($username) {
$result = $this->query('SELECT id
FROM users
WHERE username = \''.$this->db->real_escape_string($username).'\'');
if(!($row = $result->fetch_array(MYSQLI_ASSOC)))
die($this->form(LOGIN_USER_NONEXISTS,'lost'));
$hash = $this->session_add($row['id'],'lostpassword');
$emailcontents = sprintf("Benvolgut $namelastname, ha de seguir aquest enllaç per a restablir la seva contrasenya:\n\n%s?form=reset&reset=%s\n\nSalutacions!",$this->baseurl,$hash);
// Here you would send the reset link to an email address (the whole idea of ensuring this is the rightful owner of the account
// ... but for testing purposes , the output of the email is below
mail($username,'Restableixi la seva contrasenya', $emailcontents);
//echo "<hr>$emailcontents<hr>";
die($this->form(LOGIN_PASSWORD_LINKSENT,'reset'));
}
// On successful reset password link, allow the user to reset their password
private function password_reset($reset,$password,$password2) {
if(($error = $this->session_check($reset,'lostpassword')) < 0)
die($this->form($error,'reset'));
if($password != $password2)
die($this->form(LOGIN_PASSWORD_BADMATCH,'reset'));
elseif(strlen($password) < 8)
die($this->form(LOGIN_PASSWORD_TOOSHORT,'reset'));
$salt = openssl_random_pseudo_bytes($this->hashlength);
$hash = pack('H*',hash($this->hashfunction,$this->secret.$salt.$password));
$this->query('UPDATE sessions AS s
INNER JOIN users AS u ON s.userid = u.id
SET u.salt = \''.$this->db->real_escape_string($salt).'\',u.password = \''.$this->db->real_escape_string($hash).'\'
WHERE s.hash = UNHEX(\''.$reset.'\') AND s.sessiontype = \'lostpassword\'');
$this->query('DELETE FROM sessions
WHERE hash = UNHEX(\''.$reset.'\') AND sessiontype = \'lostpassword\'');
$this->login($this->account['username'],$password);
}
// Log out
private function logout() {
$this->query('DELETE FROM sessions
WHERE sessions.sessiontype = \'login\' AND sessions.hash = UNHEX(\''.$_COOKIE['cddzck'].'\');');
setcookie("cddzck","",time() - 3600);
$this->redirect();
}
private function redirect() {
header('Location: //'.$_SERVER['HTTP_HOST'].$this->clean_uri());
exit(0);
}
// Removes login-specific details from the current URI
private function clean_uri() {
return preg_replace("'[?&](form|reset|logout|cddzck)=[^&]+'",'',$_SERVER['REQUEST_URI']);
}
// Validate that a user-provided session is syntactically valid
private function session_valid($hash) {
return preg_match("'^[a-f0-9]{".($this->hashlength*2)."}$'",$hash);
}
// Check a session cookie to see whether it's valid, and logged in or not
private function session_validate() {
if(!isset($_COOKIE['cddzck']) || !$this->session_valid($_COOKIE['cddzck']))
die($this->form(LOGIN_SESSION_EXPIRED,'signin'));
if($this->session_check($_COOKIE['cddzck'],'login') < 0) {
setcookie("cddzck","",time() - 1800);
die($this->form(LOGIN_SESSION_EXPIRED,'signin'));
}
return $this->account['id'];
}
// Look up the hash table for a given session in a given context
private function session_check($hash,$type = 'login') {
$result = $this->query('SELECT u.id,u.flags,u.created,u.lastlogin,u.username
FROM sessions AS s
INNER JOIN users AS u ON s.userid = u.id
WHERE s.hash = UNHEX(\''.$hash.'\') AND s.sessiontype = \''.$type.'\';');
if(!$this->account = $result->fetch_array(MYSQLI_ASSOC)) {
unset($_GET['reset']);
die($this->form(LOGIN_PASSWORD_LINKEXPIRED,'reset'));
}
return 0;
}
// MySQL queries
private function query($sql) {
$result = $this->db->query($sql) or die(__LINE__.' '.$this->db->error.' '.$sql);
return $result;
}
}
?>
FILE: access.php
<?php
// Call me admin.php
$db = new mysqli('localhost','dbusr','dbpasswd','dbname'); // Change these details to your own
include_once('login.php');
$_auth = new auth($db); // Anything past here is logged in
printf('<span style="float: right; margin-right: 29px;">[ Sortir ]</span>');
?>
Extend your Auth-Class in login php with that method:
public function getUsername()
{
return isset($this->account['id']) ? $this->account['username'] : "No user found.";
}
After you login you can access that username :
<?php
// Call me admin.php
$db = new mysqli('localhost','dbusr','dbpasswd','dbname'); // Change these details to your own
include_once('login.php');
$_auth = new auth($db); // Anything past here is logged in
//Username:
$username = $_auth->getUsername();
printf('<span style="float: right; margin-right: 29px;">[ Sortir ]</span>');
?>

Add an array within an array list Codeigniter 3?

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.

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 />";
}
}

insert two times with redirect using slim framework

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?

PHP. Calling function from a different class.

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();
}
?>

Categories