I tried to make a database where I could store people their IP address, so the same IP address couldn't subscribe twice. I already know how to get someone there IP adress but I don't know how to insert it into my database. Here is my code:
// Connect to MySQL
$mysqli = new mysqli( '***', '***', '***', 'inschrijven' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Kan niet verbinden met database. Probeer het later opnieuw. ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = "INSERT INTO inschrijven ( naam, email, aantal,ip) VALUES ( '{$mysqli->real_escape_string($_POST['naam'])}', '{$mysqli->real_escape_string($_POST['email'])}', '{$mysqli->real_escape_string($_POST['aantal'])}'";
// validate agree unless you want to add 'checked' to one of the values
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "U bent succesvol ingeschreven! U heeft bootnummer: {$mysqli->insert_id}. Op de naam: . U krijgt hiervan nog een bevesteging op uw mail, uw bootnummer kan nog veranderen. Hopelijk zien we u op de BotenBouwDag 2016!";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
}
?>
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>
Welkom op de officiële site van de BotenBouwDag 2016
</title>
</head>
<body>
<form method="post" action="">
<input name="naam" id="naam" type="text">
<input name="email" id="email" type="email" autocomplete="off">
<input name="aantal" id="aantal" type="number">
<input type="radio" name="eten"> Ja
<input type="radio" name="eten"> Nee
<input type="submit" id="submit" value="Verstuur Informatie">
</form>
<div id="ip"></div>
<div id="address"></div>
<script type="text/javascript">
$.get("http://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
document.getElementById('city').value = response.city;
}, "jsonp");
</script>
</body>
</HTML>
If I got it right.You shoud add this to the your value part
VALUES ( '{$mysqli->real_escape_string($_POST['naam'])}', '{$mysqli->real_escape_string($_POST['email'])}', '{$mysqli->real_escape_string($_POST['aantal'])}','{$mysqli->real_escape_string($_SERVER['REMOTE_ADDR'])}'
Related
I am making a very simple movie database, with the possibility to update the movies that are in it. All you have to do is fill in the fields underneath the table. However, when you fill in the id and only one other field, like film_id, the description etc. are erased from the table. How do i make sure that it's possible to change only one thing?
The code for the page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<?php
session_start(); //Start sessie.
function is_logged() {
if (isset($_SESSION['username'])) return true;
return false; //De gebruikersnaam wordt gecontroleerd
}
if(!is_logged()){
header("Location: sign-in.php"); //Als de gebruiker naar overzichtlogin.php
gaat, zonder dat hij of zij is ingelogd, worden ze doorgestuurd naar de
login pagina.
}
require_once('db_const.php'); //De gegevens voor het maken van de verbinding
met de database staan in dit bestand gedeclareerd.
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$mysqli){
die("Connection failed: ".mysqli_connect_error()); //Als de verbinding niet
lukt zal deze niet werken.
}
?>
<?php $current = 'secured'; ?> <!-- Om aan te geven dat men zich op de
beveiligde overzichtspagina bevindt, wordt gebruik gemaakt van deze
variabele. Current krijgt nu de waarde 'secured', waardoor de button waar
'secured' staat een kleur krijgt. -->
<div class="header">
<?php
if(isset($_SESSION['username'])){
require_once("headersecured.php"); //Indien de gebruiker ingelogd is, wordt
'headersecured.php' gebruikt als header.
}else{
require_once("header.php"); //Indien de gebruiker niet is ingelogd, wordt
header.php gebruikt als header.
}
?>
</div>
<h1>Filmoverzicht</h1>
<?php
$sql = "SELECT film_id, title, description, release_year, rating FROM
films"; //De gewenste gegevens uit de database worden geselecteerd.
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo "<table style='border: solid 1px grey; margin-left: auto; margin-right:
auto; margin-top:50px;'><tr><th>ID</th> <th>Titel</th> <th>Beschrijving</th>
<th>Jaar</th> <th>Rating</th> <th> </th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" .$row["film_id"] . "<td>" .$row["title"] . "<td>" .
$row["description"] . "<td>" . $row["release_year"]. "<td> " .
$row["rating"]. "<td> " . '<td><a class="alert" href="deletemovie.php?
id='.$row['film_id'].'" >
</i>'?> VERWIJDER <?php '</a></td>';
} //De beschikbare gegevens worden weergegeven.
echo "</table>";
} else {
echo "0 results";
}
?>
<br><br>
<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>"> <!--De
bewerkfunctie wordt op dezelfde pagina uitgevoerd.-->
<h2>Films bewerken</h2>
<input name="film_id" required="required" placeholder="ID">
<input name="title" placeholder="Titel film">
<textarea id="textarea" name="description" cols="20" rows="5"
placeholder="Beschrijving"></textarea>
<input name="release_year" placeholder="Uitkomstjaar">
<input name="rating" placeholder="Beoordeling">
<input id="submit" name="submit" type="submit" value="Wijzigen"> <!-- In
deze
invulvelden kunnen nieuwe gegevens worden ingevoerd, zodat de films worden
aangepast. -->
<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"]; //Slaat de gegevens voor het ingevoerde ID op in
een
variabele.
$title = $_POST["title"]; //Slaat de gegevens voor de ingevoerde titel op in
een
variabele.
$description = $_POST["description"]; //Slaat de gegevens voor de ingevoerde
beschrijving op in een variabele.
$year = $_POST["release_year"]; //Slaat de gegevens voor het ingevoerde jaar
op
in een variabele.
$rating = $_POST["rating"]; //Slaat de gegevens voor de ingevoerde rating op
in een variabele.
$sql = "UPDATE films SET film_id = '$film', title = '$title', description =
'$description', release_year = '$year', rating = '$rating' WHERE film_id =
$film"; //De tabel 'films' in MySQL wordt geselecteerd, de gegevens die in
de
variabelen zijn opgeslagen worden gewijzigd in de database.
if (mysqli_query($mysqli, $sql)) { // Voert de actie uit
echo "<br>"; // Wit ruimte
echo "<br>"; // Wit ruimte
echo "<br>"; // Wit ruimte
echo "Succesvol aangepast!"; // Geeft aan dat het aangepast is
echo "<br>"; // Wit ruimte
echo "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>"; //
een link waar de gebruiker terug kan gaan naar de vorige pagina
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli); // geef fout
melding aan de gebruiker als het mis gaat
}
}
?>
</form>
<?php
$mysqli->close(); //Verbinding wordt verbroken.
?>
<div class="footer">
<?php include 'footer.php';?> <!-- De footer wordt opgehaald. -->
</div>
</body>
</html>
The problem is when the $_POST["description"] is not defined the value of $description is taken as NUll. In order to avoid this the Update query has to be constructed dynamicaly.
$sql = "UPDATE films SET film_id = '$film', title = '$title'";
if(isset($_POST["description"])) {
$description = $_POST["description"];
$sql .= ", description = $description"
}
$sql .= ", release_year = '$year', rating = '$rating' WHERE film_id = $film";
In this case when the $_POST["description"] is not set the query becomes "UPDATE films SET film_id = '$film', title = '$title', release_year = '$year', rating = '$rating' WHERE film_id = $film";
or else the query becomes "UPDATE films SET film_id = '$film', title = '$title', description = $description, release_year = '$year', rating = '$rating' WHERE film_id = $film";
You have to check on multiple values for validation, because you want that at least one field (other than film ID) is completed. If none provided, than notify the user. This validation should be made on client-side (with js, jquery, validation plugins, etc).
Then, you must dynamically build your sql statement. Use sprintf()
function for such "complex" constructs. It's very elegant. In it, the %s parts are placeholders for the variables.
Please notice the UPDATE statement: you don't want to update the
film_id field! You must use it ONLY to select the one record which
you want to update (e.g. just in WHERE clause). If you want to
change film_id, you must reinsert a record with the new id.
You are missing the <body> tag.
I was bringing last php code UNDER the </form> tag.
As a general rule: separate display logic from server processing.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>My films</title>
</head>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', 'root', 'tests');
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<!-- ... -->
<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>">
<h2>Films bewerken</h2>
<input name="film_id" required="required" placeholder="ID">
<input name="title" placeholder="Titel film">
<textarea id="textarea" name="description" cols="20" rows="5" placeholder="Beschrijving"></textarea>
<input name="release_year" placeholder="Uitkomstjaar">
<input name="rating" placeholder="Beoordeling">
<input id="submit" name="submit" type="submit" value="Wijzigen">
</form>
<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"];
$title = $_POST["title"];
$description = $_POST["description"];
$year = $_POST["release_year"];
$rating = $_POST["rating"];
$message = '<br/><br/><br/>';
if (!isset($film)) {
$message .= 'You must provide the film ID!';
} elseif (
(!isset($title) || empty($title)) &&
(!isset($description) || empty($description)) &&
(!isset($year) || empty($year)) &&
(!isset($rating) || empty($rating))
) {
$message .= 'You must provide at least one field for the selected film ID!';
} else {
$sql = sprintf(
"UPDATE films SET %s%s%s%s WHERE film_id = %s"
, isset($title) ? "title = '$title'" : ""
, isset($description) ? ", description = '$description'" : ""
, isset($year) ? ", release_year = '$year'" : ""
, isset($rating) ? ", rating = '$rating'" : ""
, $film
);
if (mysqli_query($mysqli, $sql)) {
$message .= "Succesvol aangepast!";
$message .= "<br>";
$message .= "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>";
} else {
$message .= "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
}
echo $message;
}
$mysqli->close();
?>
</body>
</html>
EDIT 1:
I recommend you to use exception handling. Here is an example:
try {
// Connect to db.
$mysqli = new mysqli('localhost', 'root', 'root', 'tests');
if (!isset($mysqli) || !$mysqli) {
throw new Exception("Connection failed: " . mysqli_connect_error());
}
// Run query on db.
$query = mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception('The statement can not be executed!');
}
$mysqli->close();
} catch (Exception $exception) {
echo $exception->getMessage();
/*
* OR display the whole error information.
* But only in the development stage!
*/
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
Don't forget to add a <title> tag to your page.
bringing trouble again, I have a PHP form with which I receive information (name and email) and send the information by email and in turn allows downloading a file with JS validation, if I remove sending email, save the information in MySQL but if I put sending mail, do not save the info ...
Here´s the code from index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Muestra Gratuita</title>
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="shortcut icon" href="img/favicon.ico">
<div id="fb-root"></div>
<script type="text/javascript">
function validar(){
var copia = document.getElementById("txtcopia").value;
var captcha = document.getElementById("captcha").value;
if (copia == captcha) {
window.open("muestra/Corazon_prodigo.pdf", "_blank");
}else{
alert("El codigo ingresado no coincide");
}
}
</script>
<script type="text/javascript">
document.oncontextmenu = function(){return false;}
</script>
</head>
<body>
<div class="container" style="padding-top : 50px;">
<div class="row">
<div class="col-md-6">
<div class="display-block">
<img class="img-responsive center-block" src="img/muestra.jpg">
</div>
</div>
<div class="col-md-6">
<p class="lead">
Por favor completa el formulario para que puedas descargar
<strong>GRATIS</strong>
una muestra (Primeras páginas) del libro Corazón Pródigo:
<br>
</p>
<div class="alert" style="display: none" role="alert"></div>
<form class="email-form" method="POST" action="send.php">
<div class="form-group">
<label for="name">Nombre Completo</label>
<input class="form-control" name="name" type="text" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" name="email" type="email" required>
</div>
<br>
<label class="lead" for="txtcopia">Introduce el texto del campo de abajo</label>
<input class="form-control" type="text" name="txtcopia" id="txtcopia" size="10">
<br>
<br>
<input class="captcha" type="text" name="captcha" id="captcha" value=<?php echo captcha(); ?> size="8" readonly>
<br>
<br>
<br>
<button id="buscarbtn" class="btn btn-success" type="submit" value="registrar" name ="buscarbtn" onclick="validar();">Suscribirse</button>
<br>
<br>
<a class="download_button btn btn-lg btn-success center-block" style="display:none" download="" href="muestra/Corazon_prodigo.pdf">Descarga Ahora</a>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
#error_reporting(0);
$sqlhost = 'localhost';
$sqluser = 'root';
$sqlpass = '';
$sqldb = 'registro';
$sqltable= 'registro';
function captcha() {
$k="";
$param="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$max=strlen($param)-1;
for ($i=0; $i<6; $i++) {
$k.=$param{mt_rand(0,$max)};
}
return $k;
}
$db = mysqli_connect($sqlhost, $sqluser, $sqlpass, $sqldb); //Nuestra variable para establecer la conexión a la base de datos
if(!$db){die("Error al conectar con la db" . mysql_error());}
$name = isset($_POST['name']) ? $_POST['name'] : NULL; // Tomamos el texto del input "nombre"
$email = isset($_POST['email']) ? $_POST['email'] : NULL; // Tomamos el texto del input "apellido"
$date = date('Y-m-d');
// Insertaremos la información a la tabla Nombre y Apellido, donde VALUES declara el texto que ingresaremos
$query = "INSERT INTO ".$sqltable."(name, email, date) VALUES('".$name."', '".$email."', '".$date."');";
mysqli_select_db($db,$sqldb); //verificaremos la conexión a nuestra base de datos
$insert_value = mysqli_query($db, $query); // Declaramos la variable $insert_value para usarla cómo un bool, en caso de que esta consulta falle
if(!$insert_value) //Crearemos la consulta
die('Error: ' . mysqli_error($db)); // Si falla, nos mostrará este texto, seguido del error.
mysqli_close($db); // Detenemos la conexión de la base de datos
?>
Here´s the code from send.php:
<?php
$para = "example#example.com";
require 'PHPMailerAutoload.php';
$mail=new phpmailer();
$mail->PluginDir = "includes/";
$mail->Mailer = "smtp";
$mail->Host = "mail.example.com";
$mail->SMTPAuth = true;
$mail->Username = "contact#example.com";
$mail->Password = "H1hs4h45";
$mail->From = "contact#example.com";
$mail->FromName = "contacto WEB";
$mail->Timeout=30;
$mail->AddAddress($para);
$mail->Subject = "NUEVO USUARIO REGISTRADO";
$mail->Body = $_POST['name'].chr(13).chr(10).$_POST['email'];
$mail->IsHTML(true);
if($mail->Send())
{
echo'<script type="text/javascript">
alert("Enviado Correctamente");
window.location="http://example.com/index.php"
</script>';
}
else{
echo'<script type="text/javascript">
alert("NO ENVIADO, intentar de nuevo");
window.location="http://example.com/index.php"
</script>';
}
?>
So the question is, how can I run the email sending and turn to save the information in MySQL at the same time?
Because, if I put send.php content in the same file index.php or vice versa, when the page loads it generates a loop and sends email every 30 seconds, and I forgot to say, when the email are sent, it generates a MySQL row but it is empty...
I'm trying to make a simple form that sends the user input to my email. I don't know PHP so I'm having some trouble here. I can't make the form include the checkboxes' results in the mail. I tried several times but I can't make it work. It's in spanish, sorry for that!
Here is the code:
contactoformescritorio.php:
<?php
$where_form_is = "contacto.html".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
mail("MY#MAIL.com","Formulario de pedido de copias","Form data:
Nombre: " . $_POST['cd-name'] . "
Email: " . $_POST['cd-email'] . "
Tamanio: " . $_POST['tamanio'] . "
Acabado: " . $_POST['acabado'] . "
Incluir en la cotizacion: " .implode(',',$_POST['agregados'])."\n" . "
Foto elegida e información adicional: " . $_POST['cd-textarea'] . "
.
");
include("confirm.html");
/*
* Procesar el formulario unicamente si el usuario lo envió. En cambio,
* si se accede directamente a esta página, redirigir al formulario.
*/
if ($_SERVER['REQUEST_METHOD'] == "POST") {
function check_input_value($input_value) {
// Remove extra spaces of strings (beginning and end)
$input_value = trim($input_value);
// Prevent XSS
$input_value = htmlspecialchars($input_value);
return $input_value;
}
// Obtenemos los valores que el usuario ingresó
$tamanio = $_POST['tamanio'];
$acabado = $_POST['acabado'];
$tamanio = check_input_value($tamanio);
$acabado = check_input_value($acabado);
if (empty($tamanio) || (empty($acabado)) || (empty($agregados))) {
echo "Error: sin completar";
exit;
}
echo $tamanio . "<br />";
echo $acabado . "<br />";
// Muestra los checkbox seleccionados por el usuario
if (!empty($_POST['agregados'])) {
foreach ($_POST['agregados'] as $agregados) {
echo $agregados . "<br />";
}
}
} else {
header("Location: formulario.php");
}
?>
A friend helped me with the form so it may be a little messy as I copied and pasted some parts.
contacto.html
<form class="cd-form floating-labels" name="htmlform" method="post" action="contactoformescritorio.php">
<fieldset>
<legend>Información personal</legend>
<div class="error-message">
<p>Por favor ingresa un email valido</p>
</div>
<div class="icon">
<label class="cd-label" name="cd-name" for="cd-name">Nombre</label>
<input class="user" type="text" name="cd-name" id="cd-name" required>
</div>
<div class="icon">
<label class="cd-label" name="cd-email" for="cd-email">Email</label>
<input class="email error" type="email" name="cd-email" id="cd-email" required>
</div>
</fieldset>
<fieldset>
<legend>Informacion de la impresion</legend>
<div>
<h4>Tamaño</h4>
<p class="cd-select icon">
<select class="size" name="tamanio" id="cd-size">
<option value="0">Seleccionar Tamaño</option>
<option value="1">Impresion 20x30</option>
<option value="2">Iman de 6 fotos 5x5</option>
<option value="3">Tamaño 3</option>
</select>
</p>
</div>
<div>
<h4>Acabado</h4>
<ul class="cd-form-list">
<li>
<input type="radio" name="acabado" value="mate" id="mate" checked="checked"/><label for="mate">Mate</label>
</li>
<li>
<input type="radio" name="acabado" value="brillo" id="brillo"/><label for="brillo">Brillo</label>
</li>
</ul>
</div>
<div>
<h4>Agregar a la cotización</h4>
<ul class="cd-form-list">
<li><input type="checkbox" name="agregados[]" value="marco" id="marco"><label for="marco">Marco</label></li>
<li><input type="checkbox" name="agregados[]" value="envio" id="envio"><label for="envio">Envio (indicar direccion)</label></li>
</ul>
</div>
<div class="icon">
<label class="cd-label" for="cd-textarea">Foto elegida e información adicional</label>
<textarea class="message" name="cd-textarea" id="cd-textarea" required></textarea>
</div>
<div>
<input type="submit" value="Enviar mensaje">
</div>
</fieldset>
</form>
Your checkboxes are both of the name agregados[], which makes them an array. You currently handle them via implode, then later with a foreach.
Before your mail, run a foreach like this
if (!empty($_POST['agregados'])) {
foreach ($_POST['agregados'] as $key=>$value) {
if ($key > 0) {
$agregados .= ", $value";
} else {
$agregados .= "$value";
}
}
} else {
$agregados .= "(nothing selected)";
}
This will set the variable $agregados with the values that was selected from the checkboxes, and if nothing is selected, display such a message instead.
Then, in your mail, replace the line that handles the checkboxes with the variables.
Replace:
Incluir en la cotizacion: " .implode(',',$_POST['agregados'])."\n" . "
with
$agregados
Also, please know that your mail will be sent regardless when you enter contactoformescritorio.php, as there is no checking if a form has been sent to it. The check you are performing (if ($_SERVER['REQUEST_METHOD'] == "POST")) comes after that.
As a final note, not one that's related to your question directly, your select has no require-attribute, so your PHP script exits if nothing is selected (where you are checking of one of the three statements are empty). Just put a required attribute in your select, such as this
<select class="size" name="tamanio" id="cd-size" required>
Then your Seleccionar Tamaño can be set to a line like this
<option value="" selected style="display:none;">Seleccionar Tamaño</option>
This will make your form more "user-friendly", and not make the user fill in the form all over again if they forget to select something from the dropdown. Just a tip, nothing you really have to do.
So I've had to make a simple phonebook in PHP, but right now it simply echos the text beneath the form, I however, want it to fill it in the form which says: Phonenumber (When you type in the exact name of someone you it echos their phonenumber)
Here's the Form:
<form action="" method="post">
Naam: <br><input type="text" name="name" /><br>
Telefoonnummer: <br><input type="text" name="phonenumber" disabled />
<input type="submit" value="submit" />
</form>
and here's the PHP (I'm Dutch btw so some of the text is in Dutch):
<?php
if(isset($_POST['name'])) {
$formNaam = $_POST['name'];
$naamPersoon = array ("Ilja Clabbers","Piet Paulusma","Gerrit Zalm");
$telefoonNummer = array ("038-4699776","0568-121212","010-2311512");
if(empty($formNaam)) {
echo 'Vul een veld in.';
} else if ($formNaam == $naamPersoon[0]){
echo "Het telefoonnummer van " . $naamPersoon[0] . " is " .$telefoonNummer[0];
} else if ($formNaam == $naamPersoon[1]){
echo "Het telefoonnummer van " . $naamPersoon[1] . " is " .$telefoonNummer[1];
} else if ($formNaam == $naamPersoon[2]){
echo "Het telefoonnummer van " . $naamPersoon[2] . " is " .$telefoonNummer[2];
} else {
echo "Deze naam staat niet in het archief";
}
}
?>
So basically what I'd like to know is; How do you get the phonenumber belonging to a persons name to be shown in the Form where it says 'Telefoonnummer:'?
A neater solution would be to make a single associative array with key => value pairs:
$naamPersoon = array (
"Ilja Clabbers" => "038-4699776",
"Piet Paulusma" => "0568-121212",
"Gerrit Zalm" => "010-2311512",
);
Then your code would be:
$phonenumber = '';
if (array_key_exists($formNaam, $naamPersoon)) {
echo "Het telefoonnummer van " . $formNaam . " is " . $naamPersoon[$formNaam];
$phonenumber = $naamPersoon[$formNaam];
} else {
echo "Deze naam staat niet in het archief";
}
Alternatively you could keep your two arrays as they are and use array_search to find the index of the name in the first array, then use it as the index you check in the second array
$phonenumber = '';
$index = array_search($formNaam, $naamPersoon);
if ($index === false) {
echo "Deze naam staat niet in het archief";
} else {
echo "Het telefoonnummer van " . $formNaam . " is " . $telefoonNummer[$index];
$phonenumber = $telefoonNummer[$index];
}
Either way you can then use the assigned variable $phonenumber to add the number to the form by echoing it out as the input's value. At which point you can take out the echos if you wish.
<form action="" method="post">
Naam: <br><input type="text" name="name" /><br>
Telefoonnummer: <br><input type="text" name="phonenumber" value="<?=htmlspecialchars($phonenumber)?>" disabled />
<input type="submit" value="submit" />
</form>
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);
}