Validate form before submitted (Check all fields are entered) - php

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

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

Trying to bring data with an input

I'm trying to populate some inputs depending by other inputs, but when i fill the first input thishow me an error of problems to connect with the data base
this is my HTML
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>POC Ajax Cliente</title>
</head>
<body>
<div id="cliente">
<form action="" method="POST">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" value="" placeholder="Nombre.." />
<br />
<label for="direccion">Dirección</label>
<input type="text" id="direccion" name="direccion" value="" placeholder="Dirección.." />
<br />
<label for="telefono">Teléfono</label>
<input type="text" id="telefono" name="telefono" value="" placeholder="Teléfono..." />
</form>
</div>
<div id="estado">Esperando input.</div>
<!-- Scripts -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script type="text/javascript" src="cliente.js"></script>
</body>
</html>
this is my client.js
$(function(){
/* Ponemos evento blur a la escucha sobre id nombre en id cliente. */
$('#cliente').on('blur','#nombre',function(){
/* Obtenemos el valor del campo */
var valor = this.value;
/* Si la longitud del valor es mayor a 2 caracteres.. */
if(valor.length>=3){
/* Cambiamos el estado.. */
$('#estado').html('Cargando datos de servidor...');
/* Hacemos la consulta ajax */
var consulta = $.ajax({
type:'POST',
url:'cliente.php',
data:{nombre:valor},
dataType:'JSON'
});
/* En caso de que se haya retornado bien.. */
consulta.done(function(data){
if(data.error!==undefined){
$('#estado').html('Ha ocurrido un error: '+data.error);
return false;
} else {
if(data.telefono!==undefined){$('#cliente #telefono').val(data.telefono);}
if(data.direccion!==undefined){$('#cliente #direccion').val(data.direccion);}
$('#estado').html('Datos cargados..');
return true;
}
});
/* Si la consulta ha fallado.. */
consulta.fail(function(){
$('#estado').html('Ha habido un error contactando el servidor.');
return false;
});
} else {
/* Mostrar error */
$('#estado').html('El nombre tener una longitud mayor a 2 caracteres...');
return false;
}
});
});
and this is my client.php where i make the consult from the DB
<?php
require 'config/Conexion.php';
if(!empty($_POST['nombre'])){
$nombre = $_POST['nombre'];
$sql = "SELECT * FROM usuarios WHERE nombre = '.$nombre.'";
$stmt = $pdo->prepare($sql);
$stmt ->execute();
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($arrDatos){
foreach ($arrDatos as $row) {
$return = array ('telefono' => $row['telefono'], 'direccion' => $row['direccion']);
}
} else {
$return = array('error'=>'El nombre no esta guardado en la base de datos');
}
die(json_encode($return));
}
when i put something in the first input the message that apears is that there was a problem with the connection to the Data Base

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);

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

$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!

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!

Categories