Invalid argument for foreach... to a global $var; - php

$form[0]= '<!DOCTYPE HTML><html>
<head><meta charset="utf-8"></head>
<body>';
$form[1]= '<div class="logo img-center"></div><div class="box-shadow fondo-blanco">';
$form[2]= '<p class="mostrar caja texto-advertencia">Para acceder a este sitio debes iniciar sesión nuevamente.</p>';
$form[3]= '<form method="post" action="" class="caja borde-transparente " style="margin: 14px auto;width:400px;max-width:100%;">';
$form[4]='<span class="mostrar texto-advertencia p">
Clave o nombre de usuario incorrectos! <br> Debes iniciar sesión con una cuenta con acceso de administrador para ver este contenido.</span>';
$form[5]='<span class="mostrar texto-advertencia p">Haz realizado demasiados intentos fallidos para iniciar la sesión. Intentá nuevamente en unos minutos.';
$form[6]= '<label class="borde-identidad texto-gris-oscuro caja-i caja con-separador m con-relieve-3"><span class="i-storekey"></span>Iniciar sesión:</label>
<input class="input borde-gris" type="text" placeholder="Usuario" name="username" autofocus>
<input class="input borde-gris" type="password" placeholder="Contraseña" name="password">';
$form[7]= '<div class="checkbox" style="font-size:16px">
<input id="mycheckbox" type="checkbox" name="remember-me" value="1">
<label for="mycheckbox" class="texto-gris-oscuro"> Mantener la sesión iniciada
</label>
</div>';
$form[8]= '<input type="submit" value="Ingresar" class="btn btn-info">
</form></body></html>';
if (!function_exists('echo_formulario')){
function echo_formulario($rough=NULL){
global $form;
foreach ($form as $key=>$html):
#some code here...
endforeach;
}
}
The foreach loop gives an "invalid argument" warning. It worked on localhost yesterday though...
Is there a problem in the way the $form var is being called?

Problem 1: $html is not defined in your code.
Problem 2: There is a colon : at the end of your foreach
Problem 3: A lot of your opening brackets { do not have a closing bracket
Try this first
if (!function_exists('echo_formulario')){
function echo_formulario($rough=NULL){
global $form;
foreach ($form as $key=>$html){
echo $key;
}
}
}
If that doesn't work try using foreach ($form as $key) instead.
if (!function_exists('echo_formulario')){
function echo_formulario($rough=NULL){
global $form;
foreach ($form as $key){
echo $key;
}
}
}
Hope it works!

Related

Incomplete PHP website

I have a problem with my form, when I get in my website with Xampp, the webpage is not completed, doesn't appear the "region" combo box, the "fono" text field and the buttons, I don't know why it happens :( I wonder if someone could help me with this issue, please, as I fixed the bracket problems, now this problem is really freaking me out indeed.
<!DOCTYPE html>
<html>
<head>
<title>Formulario de datos</title>
<meta charset="UTF-8">
<script src="js/jquery.js"></script>
<script src="js/NumeroLetra.js"></script>
<script src="js/Hora.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery.Rut.js"></script>
<script src="js/jquery.validate.js"></script>
</head>
<body onLoad="IniciarReloj24()">
<?php
ini_set('error_reporting',0);
include ('funciones.php');
?>
<form action = " " method="post">
<?php
//comprobamos el evento del boton
if ($_POST['btnRutBuscar'] == "Buscar"){
$cnn = Conectar();
//concatenamos los inputs para realizar el formato del rut
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
//sentencia sql anidada entre registro y regiones
$sql = "select re.rut, re.nombres, re.apellidos, re.fnac, re.sexo, r.id, r.region, re.fono from registro re, regiones r where (re.region = r.id) and (re.rut = '$rutt')";
$rs = mysqli_query($cnn, $sql);
while ($row = mysqli_fetch_array($rs)){
$rut = $row['rut'];
$nom = $row['nombres'];
$ape = $row['apellidos'];
$fna = $row['fnac'];
$sex = $row['sexo'];
//recogemos el id de la tabla regiones que sera utilizada en el combo box de regiones
$id = $row['id'];
$reg = $row['region'];
$fon = $row['fono'];
//se les añade los value a los inputs para poder recibir los valores de la base de datos
}
}
?>
<center><h1>Formulario de datos: todo en uno</h1></center>
<center><h2>Creado por Matías Cáceres y Francisco Tello</h2></center>
<br>
<br>
<div align="center"><label>Rut:</label>
<input type="text" name="txtRut" id="txtRut" onkeypress="ValidaSoloNumeros()" value="<?php echo $rut?>" /> -
<input type="text" name="txtDigito" id="Verificador" size="2" onkeypress="ValidaSoloNumeros()" />
<input type="submit" name="btnRutBuscar" id="btnBuscar" value="Buscar" /></div>
<br>
<br>
<div align="center"><label>Nombres:</label>
<input type="text" name="txtNombres" id="txtNombres" onkeypress="txNombres()" value="<?php echo $nom ?>" />
<br>
<br>
<div align="center"> <label>Apellidos:</label>
<input type="text" name="txtApellidos" id="txtApellidos" onkeypress="txNombres()" value="<?php echo $ape ?>"/>
<br>
<br>
<div align="center"><label>Fecha de Naciemiento:</label>
<input type="date" name="txtFecha" value="<?php echo $fnac ?>" />
<br>
<br>
<div align="center"><label>Sexo:</label>
<select name="txtSexo">
<option value=""><?php $sex ?></option>
<option value = "Masculino">Masculino</option>
<option value = "Femenino">Femenino</option>
</select></div>
<br>
<br>
<div align="center"><label>Región:</label>
<?php
$cnn=Conectar();
$sql="select region from regiones";
$rs = mysqli_query($cnn,$sql); ?>
<select name="txtRegion">
<option value=""><?php echo $reg ?></option>
<?php while ($row=mysqli_fetch_array($rs))
{echo '<option>'.$row["region"];}
?>
</select>
</div>
<br>
<br>
<div align="center"><label>Fono:</label>
<input type="text" name="txtFono" id="txtFono" onkeypress="ValidaSoloNumeros()" value="<?php echo $fon ?>" />
</div>
<br>
<br>
<table>
<td><input type="submit" name="btnAgregar" id="btnAgregar" value="Agregar"/></div></td>
<td><input type="submit" name="btnModificar" id="btnModificar" value="Modificar"/></div></td>
<td><input type="submit" name="btnEliminar" id="btnEliminar" value="Eliminar"/></div></td>
<td><input type="submit" name="btnVerTodos" id="btnVerTodos" value="Ver Todos"/></div></td>
</table>
<?php
if($_POST['btnAgregar']=="Agregar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sexo = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFono'];
$sql = "insert into registro values('$rutt','$nom','$ape','$fna','$sexo','$reg','$fon')";
//este if lo acabo de colocar, es mas que nada para saber si ocurrio algo malo al momento de ejecutar la funcion (***** El if es necesario en todos los botones*****)
#Comprobar el nombre de las variables
if (empty($rut) || empty($nom) || empty($ape) || empty($fnac) || empty($sex) || empty($reg) || empty($fon)) {
echo "<script>alert('Todos los campos son obligatorios');</script>";
if( mysqli_query($cnn,$sql)){
echo "<script>alert('Se han grabado los datos')</script>";
echo "<script>window.location='index.php'</script>";
}else{
echo "<script>alert('ocurrio un problema');</script>";
}
}
}
if($_POST['btnEliminar']=="Eliminar")
{
$cnn = Conectar();
$rut = $_POST['txtRut']."-".$_POST['txtDigito'];//es necesario concadenar los dos inputs para que funcione la consulta
$sql = "delete from registro where (rut = '$rut')";
mysqli_query($cnn,$sql);
echo "<script>alert('Se eliminó el registro')</script>";
}
if($_POST['btnModificar']=="Modificar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito']; //es necesario concadenar los dos inputs para que funcione la consulta
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sex = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFecha'];
$sql = "update registro set nombres='$nom', apellidos='$ape', fnac='$fna', sexo='$sex', region='$reg', fono='$fon' where rut='$rutt'";
mysqli_query($cnn,$sql);
echo "<script>alert('Se han editado los datos')</script>";
}
?>
</form>
<table border = '1'>
<tr>
<?php date_default_timezone_set('America/Santiago');
$vaFecha = date('d-m-y');
?>
<td>Fecha</td>
<td><input type = "text" name="caja_fecha" value = "<?php echo $vaFecha; ?>" disabled="disabled"></td>
</tr>
</table>
<form name="reloj24">
<input type="text" size="8" name="digitos" value=" " disabled="disabled">
</form>
<script>
$('#txtRut').Rut( {
digito_verificador: '#Verificador',
on_error: function(){ alert('Rut incorrecto');
$("#txtRut").val("");
$("#Verificador").val("");
}
} );
</script>
</body>
</html>
enter image description here

How to change div content in PHP?

I want to change the div's id intFrom. Content after inserting data to the database, I want the code not just echo ¡Enhorabuena!...
But replace the form with ¡Enhorabuena! I maybe, I could replace the form using AJAX.
Here is the code:
HTML
<form method="post" action="">
<div>
<select value="genero" name="genderselect" id="genero" required="required" autofocus="autofocus">
<option value="none" selected>- Selecciona Género - </option>
<option value="Mujer">Mujer</option>
<option value="Hombre">Hombre</option>
</select>
<input type="text" id="name" name="name" value="" placeholder="Nombre completo" required="required" autofocus="autofocus" />
<input type="email" id="email" name="email" value="" placeholder="Correo electrónico" required="required" />
</div>
<div>
<div class="infForm img">
<img src="http://www.miraqueguapa.com/Landings/General/img/biotherm.png" alt="Imagen Crema Aquasource Biotherm" class="biotherm">
</div>
<div class="infForm text">
<div class="legal">
<input type="checkbox" id="cblegales" value="1" name="cblegales" required="required" autofocus="autofocus">
<p>He leído y acepto la <a class="enlace_pp" href="http://www.miraqueguapa.com/content/5-privacidad-proteccion-datos" target="_blank">política de privacidad</a></p>
</div>
<input type="submit" value="ENVIAR DATOS" name="submit_form" style=" background-color: #DF2848;border: none;border-radius: 0px;color: white;width: 200px;float: right;padding-left: 50px;cursor: pointer;margin-top: -5px;" />
</div>
</div>
</form>
</div>
PHP
<?php
if (isset($_POST['submit_form'])) {
include 'connection.php';
$name=$_POST["name"];
$email=$_POST["email"];
$gender=$_POST["genderselect"];
if($gender=="none"){
echo"</br>";
echo"por favor selecciona nuestro género";
$link = null;
}
else{
$i=0;
$statement = $link->prepare("select email from webform where email = :email");
$statement->execute(array(':email' => "$email"));
$row = $statement->fetchAll();
foreach($row as $key) {
$i=$i+1;
}
if ($i !=0) {
echo" Este correo electrónico ya está registrado";
$link = null;
}
else{
$statement = $link->prepare("INSERT INTO webform(name, email, gender)
VALUES(:name, :email, :gender)");
$statement->execute(array(
"name" => "$name",
"email" => "$email",
"gender" => "$gender"
));
$link = null;
echo"¡Enhorabuena!"."<br/>";
echo"Tus datos se han enviado correctamente. A partir de ahora recibirás cada semana las últimas novedades y las mejores ofertas en Cosmética de las marcas más prestigiosas del mercado.";
}}}
?>
You need to add simple if else statement.
if (isset($_POST['submit_form'])) {
// Your code after form get submitted.
}
else {
// Show default form.
}
Just load your HMTL Code in to your PHP as a kind of "Template" with file_get_contents(__DIR__ . "Path/To/Your.html"); in to a variable and do a simple str_replace('id="your_element_id"', 'id="replace_id"', $template_variable); and echo your Template after if you just want to replace an ID.
If you want to change something within the Form, do it as i said above with str_replace('tag_you_are_looking_for', 'should_be_replaced_with', $template_variable);

Validate input-fields (texbox) BEFORE execute script

I would like to ask you, how to handle this:
Validate input-fields
if everything is OK, execute the following script which writes the fields in database
What I have till now is:
if($_SERVER['REQUEST_METHOD'] == "POST")
{
...
$checkField = "";
if (empty($_POST["tb_checkField"]))
{
$checkFieldErr = "<br> Field is required!";
}
else
{
$checkField = $_POST["tb_checkField"];
if (!preg_match("/[-a-z0-9+&##\/%?=_!:,.;]+/",$checkField))
{
$checkFieldErr = "<br> Invalid value detected!";
}
}
...
}
...
<form method="post" action="writeTodatabase.php">
<table border="0" align="center">
<tr>
<td colspan="2"><input name="tb_checkField" type="text" value="<?php echo $checkField;?>" tabindex="1" size="50" maxlength="20"/>
<span class="error"><?php echo $checkFieldErr;?></span></td>
</tr>
</table>
</form>
...
<td><p>
<input type="submit" name="submit" value="Save" tabindex="2"/>
</p></td>
So when I press the button, is directly going to execute writeTodatabase.php without checking the textbox.
So how can I tell him to go first check this values from textbox and if its ok, go and execute writeTodatabase.php?
Either you can choose to validate the input on the same page as the form, or you can do the validation on the writeTodatabase.php page.
The "action" parameter in the form tag decides where you want the _POST data to be sent. You can't have your validation code on the same page as the form when you're sending the _POST data to another page. You'll either have to send the data to the current page (either removing the action parameter, or changing it's value to the current page) or move the validation script to writeTodatabase.php.
If you want the validation code to remain on the current page, and remove the action parameter, you can use the header() function to redirect to writeTodatabase.php if the validation is successful. If you're gonna use the header() function remember to put the validation code at the top of the file, before any output.
I'm making a WEB project, and I used a form imput validations in PHP:
if($_SERVER['REQUEST_METHOD']=='POST'){
require('inc/mysqli_connect.php');
$errors=array();
/*Verifica el nombre*/
if(empty($_POST['first_name'])){
$errors[]='Verifique el campo de Nombre del participante';
}else{
$fina=mysqli_real_escape_string($dbc, trim($_POST['first_name']));
}
/*Verifica el apellido paterno*/
if(empty($_POST['ape_pat'])){
$errors[]='Verifique el campo de Apellido Paterno del participante';
}else{
$appa=mysqli_real_escape_string($dbc, trim($_POST['ape_pat']));
}
/*Verifica el apellido materno*/
if(empty($_POST['ape_mat'])){
$errors[]='Verifique el campo de Apellido Materno del participante';
}else{
$apma=mysqli_real_escape_string($dbc, trim($_POST['ape_mat']));
}
/*Verifica el genero*/
if(empty($_POST['gender'])){
$errors[]='Seleccione el Género del participante';
}else{
$gend=mysqli_real_escape_string($dbc, trim($_POST['gender']));
}
/*Verifica el correo electronico*/
if(empty($_POST['email'])){
$errors[]='Verifique el campo de Correo Electrónico del participante';
}else{
$coel=mysqli_real_escape_string($dbc, trim($_POST['email']));
}
/*and repeat the code above for all the input that you have in your form */
if(empty($errors)){
$q="INSERT INTO participante(nombre, paterno, materno, genero, correo, fechadenac, procedencia, ocupacion, asistencia, fechareg) VALUES ('$fina','$appa','$apma','$gend','$coel','$dabi','$prov','$ocup','$assi',NOW())";
$r=mysqli_query($dbc,$q);
if($r){
echo '
<p>
Nombre: <b>'.$_POST['first_name'].'</b><br />
Apellido Paterno: <b>'.$_POST['ape_pat'].'</b><br />
Apellido Materno: <b>'.$_POST['ape_mat'].'</b><br />
Genero: <b>'.$_POST['gender'].'</b><br />
Correo Electrónico: <b>'.$_POST['email'].'</b><br />
Fecha de nacimiento: <b>'.$_POST['date'].'</b><br />
Procedencia: <b>'.$_POST['provenance'].'</b><br />
Ocupación: <b>'.$_POST['ocuppation'].'</b><br />
¿Asistió? <b>'.$_POST['assistance'].'</b><br />
</p>
';
}else{
echo '
<h2><a>¡Error del Sistema!</a></h2>
<p>
El registro no pudo realizarse debido a un error del sistema. Disculpe los incovenientes.<br />
</p>
<p>
Error: '.mysqli_error($dbc).'<br />
Query: '.$q.'<br />
</p>
';
}
mysqli_close($dbc);
include ('inc/footer.html');
exit();
}else{
echo '
<p>
Revise que todo los campos hayan sido llenados correctamente.<br />
Se encontraron los siguientes errores: <br />
';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '
</p>
<p>
Ingrese los datos faltantes e intente de nuevo.
</p>
';
}
mysqli_close($dbc);
}
mysqli_connect.php has this structure:
<?php
DEFINE('DB_USER','root');
DEFINE('DB_PASSWORD','armando');
DEFINE('DB_HOST','localhost');
DEFINE('DB_NAME','flisol');
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) OR die ('No es posible conectarse a la Base de datos: '.mysqli_connect_error());
mysqli_set_charset($dbc,'utf8');
By the way, I'm using a sticky form. Enjoy it!

PHP session_start(): Cannot send session cookie

session_start(); is the first thing I call. There is no whitespace. Why am I still get this warning?
Screenshots:
Error:
[20-Feb-2014 16:52:32 America/New_York] PHP Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/feyzprod/public_html/expertlookup.ca/index.php:1) in /home/feyzprod/public_html/expertlookup.ca/index.php on line 4
[20-Feb-2014 16:52:32 America/New_York] PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/feyzprod/public_html/expertlookup.ca/index.php:1) in /home/feyzprod/public_html/expertlookup.ca/index.php on line 4
<?php session_start();
require_once('bdservice.php');
$bd = new BDService();
require_once('script.php');
if(!isset($_SESSION['specialiteBD']))
{
$sql = "SELECT * FROM Specialites";
try
{ $resultat = $bd->Select($sql); }
catch(Exception $e)
{ echo $e->getMessage(); }
if(count($resultat) != 0)
{
$newSpec= array();
foreach($resultat as $a)
{
$newSpec[] = utf8_encode($a[1]);
}
$_SESSION['specialiteBD'] = $newSpec;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Annuaire</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/ico.css" />
<script src='js/validation.js'></script>
<script>
function initialize()
{
var input = document.getElementById('where');
var componentRestrictions = {country: 'ca'};
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions(componentRestrictions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(function() {
var availableTags = [];
var ville = [];
var availableTags = <?php echo urldecode(json_encode($_SESSION['specialiteBD'])) ?>;
for(var i = 0; i < availableTags.length; i++)
{
ville.push(decode(availableTags[i]));
}
$( "#what" ).autocomplete({
minLength: 2,
source: function(req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp( "^" + re, "i" );
var a = $.grep( ville, function(item,index){
return matcher.test(item);
});
responseFn( a.slice(0,10));
}
});
});
</script>
</head>
<body>
<?php include_once("analyticstracking.php") ?>
<div class='headerBar'>
<div class='headerContent'>
<div id='logo'><a href='index.php'><img src='images/logo4.png' height='75' width='321' alt="Expert LookUp"/ title="Expert LookUp"/></a></div>
<div id='navLien'>
<table>
<tr>
<td>
<span>
<?php
if(isset($_SESSION['authentification']))
{
echo "<a href='logout.php'>déconnexion</a>
<a href='profil.php' class='blue_Button'>Profil</a>";
}
else
{
echo "<a href='enregistrement.php'>Ajouter votre entreprise</a>
<a href='connexion.php' class='blue_Button'>Connexion</a>";
}
?>
</span>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class='blur'>
<div class='blurContent'>
<div id='left'>
<p>Multiplier votre visibilité sur le web en vous inscrivant gratuitement sur notre moteur de recherche d'entreprise.</p>
<a href='enregistrement.php' class='blue_Button'>S'enregistrer</a>
</div>
<div id='right'>
<form action='search/index.php' method='get'>
<p>Trouvez un entrepreneur pour vos prochains travaux</p>
<div class='iconMan'><input type='text' name='what' id='what' size='40' placeholder="Que recherchez vous ? Ex : Plombier" required title="Veuillez indiquer votre critère de recherche." x-moz-errormessage="Veuillez indiquer votre critère de recherche." /></div><br/>
<?php
if(isset($_SESSION['invalideAdr']))
{
unset($_SESSION['invalideAdr']);
echo "<div class='iconWhere'><input type='text' style=\"border:1px solid red;\" name='where' id='where' size='40' placeholder=\"Impossible de trouver votre adresse !\" required title=\"Veuillez indiquer l\'emplacement de vos travaux.\" x-moz-errormessage=\"Veuillez indiquer l\'emplacement de vos travaux.\" /></div><br/>";
}
else
{
echo "<div class='iconWhere'><input type='text' name='where' id='where' size='40' required title=\"Veuillez indiquer l\'emplacement de vos travaux.\" x-moz-errormessage=\"Veuillez indiquer l\'emplacement de vos travaux.\" /></div><br/>";
}
?>
<div class='radio'>
<input type="radio" id="r1" name="secteur" value='1' />
<label for="r1"><span></span>Résidentiel</label>
<input type="radio" id="r2" name="secteur" value='2' />
<label for="r2"><span></span>Industriel</label>
<input type="radio" id="r3" name="secteur" value='3' checked="checked" />
<label for="r3"><span></span>Les deux</label><br/><br/>
<input type='hidden' name='page' value='1' />
<input type='submit' name='Rechercher' value='Rechercher' class='blue_Button' />
</div>
</form>
</div>
</div>
</div>
<div class='infoContent'>
<div id='info'>
<p>À propos d'Expert Lookup</p>
<span style='font-weight:bold;'>Information</span><br/>
<span>Expert LookUp est un annuaire se concentra principalement sur les entreprises dans le domaine de la construction.</span><br/><br/>
<span style='font-weight:bold;'>La simplicité même !</span><br/>
<span>Vous avez uniquement à choisir quel type d'entreprises/personnes vous recherchez, l'emplacement de votre travaux et le secteur d'activité pour faire votre recherche.
Les résultats de recherches vous seront affichées par ordre de distance et si une entreprise ne se déplace pas jusqu`à chez vous, elle ne sera pas affichée.</span><br/><br/>
<span style='font-weight:bold;'>Validation de la licence RBQ</span><br/>
<span>Nous vérifions directement à partir de la base de données de Gouvernement du Québec pour vérifier la licence RBQ des entreprises enregistrées sur notre annuaires.
Si une entreprise ne dispose pas de licence RBQ valide, cette information vous sera affichée.</span><br/><br/>
</div>
<div id='why'>
<p>Pourquoi s'enregistrer ?</p>
<table>
<tr>
<td><span>Soyez visible partout au Canada, auprès des millions d'internautes !</span></td>
<td><img src='images/blueEarth.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
<tr>
<td><span>Expert LookUp est un annuaire entièrement gratuit, aucun frais caché !</span></td>
<td><img src='images/greenMoney.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
<tr>
<td><span>Votre inscription prendra moins de 5 minutes, alors qu'attendez-vous ? Vous n'avez rien à perdre !</span></td>
<td><img src='images/clock.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
</table>
</div>
</div>
<div class='footerBar'>
<div class='footerContent'>
<a href='contact.php'>Contactez-nous</a><span> | </span>
<a href='enregistrement.php'>Ajouter votre entreprise</a><span> | </span>
<a href='connexion.php'>Connexion</a><span> | </span>
<a href='aide.php'>Aide</a><br/>
<span>© Copyright at ExpertLookUp.ca</span>
</div>
</div>
</body>
</html>
No need to check if your session_start() has already started or not. session_start() will just use the current session if there is one.
PHP Doc:
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.
Link
About the error you're receiving, I'm guessing this is due to the IF-Statement lines above it.
Well, that is probably because you already started session somewhere. I usually made solution by putting # before session_start and error was silent and session also worked.
So, #session_start(); may be solution.

Validate form before submitted (Check all fields are entered)

I'm trying to check that the fields in the form below have been filled before it can be inserted into a database e.g. display a pop up with the fields that have not been filled in. It is just a simple Registration form.
<form name="form1" method="post" action="signup_ac.php">
<strong>Sign up</strong>
Username:<input name="username" type="text" id="username" size="30">
Password:<input name="password" type="password" id="password" size="15">
Name:<input name="name" type="text" id="name" size="30">
<select name="Month">
<option selected>Month</option>
<option value="January">January</option>
<option value="Febuary">Febuary</option
</select>
<select name=Year>
<option selected>Year</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Reset" value="Reset">
</form>
How do I do this using JavaScript or jQuery.
First of all, download the jQuery validate plugin and add it to your page. Then give each input you want to make a required field a class of required. Then in jQuery:
$(function() {
$("form").validate();
});
The validate plugin is very feature rich, so you can have different types of message displayed, different validation checks etc should you require. There's more information on that in the documentation.
Finally, as with all javascript front-end validation, make sure you validate user input on the server side too, just in case a user has javascript turned off in their browser.
A simple solution (using jQuery) would be:
$(document).ready(function () {
$('input').each(function () {
var $this = $(this);
var err = $this.attr('id') + ' is required.';
var errElem = $('<span />').text(err).css({'color': 'red', 'font-weight': 'bold'});
if ($this.val().length === 0) {
$this.parent('td').append(errElem);
}
});
});
Make sure to do server-side validation as well. There are some users who disable JavaScript (and then this wouldn't run).
Below is what I will have a normal html file
<html>
<head>
<script language="javascript">
function validateMe() {
if (firstname is blank) {
alert("Enter first name");
form.first.focus();
return false;
}
if (lastname is blank) {
alert("Enter last name");
form.last.focus();
return false;
}
return true;
}
</script>
<body>
// Form here
<input type="submit" name="submit" value="Submit" onClick="return validateMe()">
</body>
</html>
if first name is blank, form never submit the form...
Another way:
if($_SERVER['REQUEST_METHOD']=='POST'){
require('inc/mysqli_connect.php');
$errors=array();
/*Verifica el nombre*/
if(empty($_POST['first_name'])){
$errors[]='Verifique el campo de Nombre del participante';
}else{
$fina=mysqli_real_escape_string($dbc, trim($_POST['first_name']));
}
/*Verifica el apellido paterno*/
if(empty($_POST['ape_pat'])){
$errors[]='Verifique el campo de Apellido Paterno del participante';
}else{
$appa=mysqli_real_escape_string($dbc, trim($_POST['ape_pat']));
}
/*Verifica el apellido materno*/
if(empty($_POST['ape_mat'])){
$errors[]='Verifique el campo de Apellido Materno del participante';
}else{
$apma=mysqli_real_escape_string($dbc, trim($_POST['ape_mat']));
}
/*Verifica el genero*/
if(empty($_POST['gender'])){
$errors[]='Seleccione el Género del participante';
}else{
$gend=mysqli_real_escape_string($dbc, trim($_POST['gender']));
}
/*Verifica el correo electronico*/
if(empty($_POST['email'])){
$errors[]='Verifique el campo de Correo Electrónico del participante';
}else{
$coel=mysqli_real_escape_string($dbc, trim($_POST['email']));
}
/*and repeat the code above for all the input that you have in your form */
if(empty($errors)){
$q="INSERT INTO participante(nombre, paterno, materno, genero, correo, fechadenac, procedencia, ocupacion, asistencia, fechareg) VALUES ('$fina','$appa','$apma','$gend','$coel','$dabi','$prov','$ocup','$assi',NOW())";
$r=mysqli_query($dbc,$q);
if($r){
echo '
<p>
Nombre: <b>'.$_POST['first_name'].'</b><br />
Apellido Paterno: <b>'.$_POST['ape_pat'].'</b><br />
Apellido Materno: <b>'.$_POST['ape_mat'].'</b><br />
Genero: <b>'.$_POST['gender'].'</b><br />
Correo Electrónico: <b>'.$_POST['email'].'</b><br />
Fecha de nacimiento: <b>'.$_POST['date'].'</b><br />
Procedencia: <b>'.$_POST['provenance'].'</b><br />
Ocupación: <b>'.$_POST['ocuppation'].'</b><br />
¿Asistió? <b>'.$_POST['assistance'].'</b><br />
</p>
';
}else{
echo '
<h2><a>¡Error del Sistema!</a></h2>
<p>
El registro no pudo realizarse debido a un error del sistema. Disculpe los incovenientes.<br />
</p>
<p>
Error: '.mysqli_error($dbc).'<br />
Query: '.$q.'<br />
</p>
';
}
mysqli_close($dbc);
include ('inc/footer.html');
exit();
}else{
echo '
<p>
Revise que todo los campos hayan sido llenados correctamente.<br />
Se encontraron los siguientes errores: <br />
';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '
</p>
<p>
Ingrese los datos faltantes e intente de nuevo.
</p>
';
}
mysqli_close($dbc);
}

Categories