i have created a simple php registration form using ajax, i have few issue in my code that when i click register button without filling any of the field
then it should throw error message saying name is required username is required like this, instead its throwing error message for each field. i.e.,
say if i simply click register button without filing any of the field then i first throw only error message saying enter name. my requirement is to throw error message at a single time for all the fields
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color:#1affff">
<div style="padding-left: 250px; padding-top:50px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "name copy" style="margin-left: 52px" value ="">
<span class="namee error"> </span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "email copy" style="margin-left: 48px" value ="">
<span class="emaile error"></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "username copy" style="margin-left:26px" value ="">
<span class="usernamee error"></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "password copy" style="margin-left:30px">
<span class="passworde error"> </span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "age copy" style="margin-left:62px" value ="">
<span class="agee error"> </span>
<br><br>
<span style="color:#0099ff"> Date Of Birth : </span>
<input type="date" name="date_of_birth" class= "date_of_birth copy" style="margin-left:14px" value ="">
<span class="date_of_birthe error"> </span>
<br><br>
<span style="color:#0099ff"> Department : </span>
<select name="department" class= "department copy" style="margin-left:14px" value ="">
<option disabled selected value> -- select an option -- </option>
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="departmente error"> </span>
<br><br>
<input type="button" class="submit" name="submit" value="Register">
</form>
</div>
</body>
<script>
$(document).ready(function(){
$(".submit").click(function(){
var name = $(".name").val();
var email = $(".email").val();
var username = $(".username").val();
var password = $(".password").val();
var age = $(".age").val();
var date_of_birth = $(".date_of_birth").val();
var department = $(".department").val();
if(name==''){$('.namee').text('Enter name'); return false}
if(email==''){$('.emaile').text('Enter email'); return false}
if(username==''){$('.usernamee').text('Enter username'); return false}
if(password==''){$('.passworde').text('Enter password'); return false}
if(age==''){$('.agee').text('Enter age'); return false}
if(date_of_birth==''){$('.date_of_birthe').text('Enter date_of_birth'); return false}
if(department==''){$('.departmente').text('Enter department'); return false}
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age + '&date_of_birth='+ date_of_birth + '&department='+ department;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "gethint.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
});
});
</script>
</html>
gethint.php
<?php
$mysqli = mysqli_connect("localhost","root","","ajax");
$username =$_POST["username"];
$password=$_POST["password"];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email=$_POST["email"];
$name=$_POST["name"];
$age=$_POST["age"];
$date_of_birth=$_POST["date_of_birth"];
$department=$_POST["department"];
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` , `date_of_birth` , `department`)
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' , '".$date_of_birth."' , '".$department."')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
?>
I've done quite a lot of fixes in your code. They include:
Set the HTML charset
Properly closing each HTML element
Fixed code indentation
Removed unnecessary spaces
Turned multiple classes into unique IDs
Changes made to your code:
Implemented FormData() object for easier form handling
Moved each error into its HTML element
Used CSS to hide each error HTML element
Changes that you still need to do:
Implement MySQLi Prepared Statements to prevent SQL injection
Implement Regular Expressions in your PHP code to verify the form data
You'll find comments in the code below explaining what's happening:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color: red;
display: none;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1 {
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2 {
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color:#1affff">
<div style="padding-left: 250px; padding-top:50px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" id="regForm" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" id="name" class="copy" style="margin-left: 52px" value ="" />
<span class="namee error">Enter name</span>
<br/><br/>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" id="email" class="copy" style="margin-left: 48px" value ="" />
<span class="emaile error">Enter email</span>
<br/><br/>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" id="username" class="copy" style="margin-left:26px" value ="" />
<span class="usernamee error">Enter username</span>
<br/><br/>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" id="password" class="copy" style="margin-left:30px" />
<span class="passworde error">Enter password</span>
<br/><br/>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" id="age" class=" copy" style="margin-left:62px" value ="" />
<span class="agee error">Enter age</span>
<br/><br/>
<span style="color:#0099ff"> Date Of Birth : </span>
<input type="date" name="date_of_birth" id="date_of_birth" class="copy" style="margin-left:14px" value ="" />
<span class="date_of_birthe error">Enter date_of_birth</span>
<br/><br/>
<span style="color:#0099ff"> Department : </span>
<select name="department" id="department" class="copy" style="margin-left:14px" value ="">
<option disabled selected value> -- select an option -- </option>
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="departmente error">Enter department</span>
<br/><br/>
<input type="button" id="submit" class="submit" name="submit" value="Register" />
</form>
</div>
</body>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var error = false;
var form = document.getElementById('regForm');
var formData = new FormData(form);
// Loop through the form data
for(var p of formData){
// Check if the form data is empty
if(p[1] === ''){
// Show the error
$('.'+p[0]+'e').show();
error = true;
}
}
// Boolean to prevent AJAX from running in case of an error
if(error){
return false;
}
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "gethint.php",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function(result){
alert(result);
}
});
});
});
</script>
</html>
<?php
//You should concatenate all error in one variable and print it error message containing div.
$mysqli = mysqli_connect("localhost","root","","ajax");
$err="";
$username =$_POST["username"];
if($username==""){
$err.="User name should not empty<br/>";
}
$password=$_POST["password"];
if($password==""){
$err.="Password should not empty<br/>";
}
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email=$_POST["email"];
$name=$_POST["name"];
$age=$_POST["age"];
$date_of_birth=$_POST["date_of_birth"];
$department=$_POST["department"];
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
$err.="Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` , `date_of_birth` , `department`)
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' , '".$date_of_birth."' , '".$department."')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
$err.="Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
if($err!=""){
echo $err;
}
?>
Related
am making this form input in my HMVC project. i want to have
input type="date"
but it happens to be the output was just like a normal textbox. what other ways can i do this or what is the error?
add_view.php
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/bootstrap/css/inputfield.css">
<html>
<div>
<fieldset>
<?php
echo form_open('Clients/create');
?>
<p>
<label class="field" for=""><span>*</span>Name:</label>
<input type = "text" name="" class ="textbox-300">
</p>
<p>
<label class="field" for=""><span>*</span>Details:</label>
<textarea name=""></textarea>
</p>
</br></br></br>
<p>
<label class="field" for=""><span>*</span>Address:</label>
<textarea name=""></textarea>
</p>
<p>
<label class="field" for=""><span>*</span>Contact Number:</label>
<input type = "text" name="" class ="textbox-300">
</p>
<p>
<label class="field" for=""><span>*</span>Contact Email:</label>
<input type = "text" name="" class ="textbox-300">
</p>
<p>
<label class="field" for=""><span>*</span>Date Added:</label>
<input type="date" name="" min="1950-01-01">
</p>
<?php
echo form_submit('submit','Save');
echo validation_errors();
echo form_close();
?>
</fieldset>
</div>
</html>
inputfield.css
textarea {
width: 51%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px black;
border-radius: 4px;
resize: none;
float:right;
}
fieldset {
width: 500px;
}
label .field{
text-align:left;
width:100px;
float:left;
font-weight: bold;
}
input.textbox-300{
width:350;
float:right;
}
fieldset p {
clear:both;
padding:5px;
}
label span, .required{
color:red;
font-weight: bold;
}
.center {
margin: auto;
padding: 10px;
}
im sorry im not good in this date thing so please help me
You are getting empty textbox result because you are not using name attribute in your input fields just add name attribute in all input fields as:
Example:
<input type = "text" name="yourName" class ="textbox-300">
<textarea name="Details"></textarea>
<textarea name="Address"></textarea>
<input type = "text" name="ContactNo" class ="textbox-300">
<input type = "text" name="Email" class ="textbox-300">
<input type="date" name="YourDate" min="1950-01-01">
date picker appears to be blank because it is not supported by mozilla fire fox. if theres any that mozilla supports please let me know. thanks
With jQuery I built some nice select boxes.
<fieldset>
<div><input type="checkbox" name="tools[RED]" value="true"><label>RED</label></div>
<div><input type="checkbox" name="tools[BLUE]" value="true"><label>BLUE</label></div>
<div><input type="checkbox" name="tools[BLACK]" value="true"><label>BLACK</label></div>
<div><input type="checkbox" name="tools[ORANGE]" value="true"><label>ORANGE</label></div>
<div><input type="checkbox" name="tools[GREEN]" value="true"><label>GREEN</label></div>
</fieldset>
To get any result in the table on the website, I have to do this:
$tools = json_encode($_POST['tools']);
which gives back a result like so:
{"RED":"true","BLACK":"true"}
However, what I need is something like this:
Red, Black, Orange, Green, Blue
So I tried this:
$test = $_POST['tools'];
$result = preg_replace('/({|:|true|}|")/', '', $test);
$test2 = preg_grep('/(^RED|^BLACK|^BLUE|^ORANGE|^GREEN|^red|^black|^blue|^orange|^green)/i', $result);
$tools = json_encode($test2);
Now, my result in the HTML website is this:
[]
My questions now are:
1) How can I check what goes back to the HTML table before it is shown there?
2) Why is the result only [] ?
Any help is welcome.
The full code is currently:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<!-- deze hieronder is nodig voor touchpad enabled sliders -->
<script src="jquery.ui.touch-punch.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<!-- selecteren van tools .backup.
<script>
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
</script>-->
<script>
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
</script>
<!-- accordion -->
<script>
$(function() {
$( "#accordion" ).accordion({
event: "click",
active: false,
collapsible: true,
autoHeight: false
});
});
</script>
<script>
$(function() {
$( "#slider-vertical" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 1,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
}
});
$( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
});
</script>
<script>
$(function() {
$( "#slider-vertical2" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 1,
slide: function( event, ui ) {
$( "#amount2" ).val( ui.value );
}
});
$( "#amount2" ).val( $( "#slider-vertical2" ).slider( "value" ) );
});
</script>
<title>Left X Right -BrainGame</title>
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script>
$(".js-example-basic-multiple").select2(); </script>
<style type="text/css">
p.label_checkbox_pair {
clear: both;
float: none;
position: relative;
}
p.label_checkbox_pair input {
left: 80px;
position: absolute;
top: 1px;
}
p.label_checkbox_pair label {
display: block;
margin-left: 90px;
width: 200px;
}
</style>
<!-- http://www.jqueryscript.net/form/jQuery-Plugin-For-Beautifying-Checkboxes-Radio-Buttons-iCheck.html -->
<script src="js/icheck.js"></script>
<script>
//oud $(document).ready(function(){
//$('input').iCheck({
//checkboxClass: 'icheckbox_polaris',
//radioClass: 'iradio_polaris',
//
//increaseArea: '20%' optional
//});
//});
$(document).ready(function(){
$('input').each(function(){
var self = $(this),
label = self.next(),
label_text = label.text();
label.remove();
self.iCheck({
checkboxClass: 'icheckbox_line-blue',
radioClass: 'iradio_line-blue',
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
});
</script>
<link href="skins/line/blue.css" rel="stylesheet">
</head>
<BODY>
<br /><br />
<table HSPACE="50" CELLPADDING="20">
<tr HSPACE=50 CELLPADDING="30">
<td>
<?php
$a=array("red","blue","black","orange","green");
$random_keys=array_rand($a,5);
$textcolours=array('red','blue','black','orange','green');
shuffle($textcolours);
echo "<right><font size=6 color='$textcolours[0]' >".$a[$random_keys[0]]."<br><br></font></right>";
echo "<right><font size=6 color='$textcolours[1]' >".$a[$random_keys[1]]."<br><br></font></right>";
echo "<right><font size=6 color='$textcolours[2]' >".$a[$random_keys[2]]."<br><br></font></right>";
echo "<right><font size=6 color='$textcolours[3]' >".$a[$random_keys[3]]."<br><br></font></rightr>";
echo "<right><font size=6 color='$textcolours[4]' >".$a[$random_keys[4]]."<br><br></font></right>";
?>
</td>
<td>
<div class="left">
<form class="span4" action="" method="post">
<fieldset>
<legend>Left X Right BrainGame</legend>
<p halign="right" margin="10px">Name: <input type="text" name="naam" ></p>
<p halign="right" margin="10px">Date: <input type="text" name="date" id="datepicker" ></p>
<!--
<label>Type<span class="required">*</span></label>
<select name="type">
<option value="Nauwkeurig">Nauwkeurig</option>
<option value="Pragmatisch">Pragmatisch</option>
</select>-->
<!--
<label>Core gericht: Functioneel / Technisch<span class="required">*</span></label>
<!--<input type="text" name="fname" placeholder="PORTEFEUILLE">
<!-- <select name="core">
<option value="Functioneel">Functioneel</option>
<option value="Technisch">Technisch</option>
</select>
-->
<!--
<label>Management<span class="required">*</span></label>
<select name="management">
<option value="0">0</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="6">6</option>
</select> -->
<!-- <label>Aantal<span class="required">*</span></label>
<input type="text" name="mi" placeholder="Middle Name"> -->
<!--
<label>Tools<span class="required">*</span></label>
<input type="text" name="tools" class="input-small" placeholder="Describe tools...."> -->
<br>
<!--
<br>
<script>$('#widget').slider-vertical();</script>
<p>
<label for="amount">Analytical:</label>
<input name="analytisch" type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-vertical" style="height:10px; width:90%;"></div>
<br>
-->
<!--
<label>Analytisch</label>
<label class="radio">
<input type="radio" name="analytisch" id="optionsRadios1" value="Ja" checked>
Ja
</label>
<label class="radio">
<input type="radio" name="analytisch" id="optionsRadios2" value="Nee">
Nee
</label> -->
<!--
<p>
<label for="amount2">Management experience:</label>
<input name="management" type="text" id="amount2" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-vertical2" style="height:10px; width:90%;"></div>
-->
<br>
<!-- <label>Eneagram<span class="required">*</span></label>
<select name="eneagram">
<option value="1 de Perfectionist">de Perfectionist</option>
<option value="2 de Helper">de Helper</option>
<option value="3 de Winnaar">de Winnaar</option>
<option value="4 de Romanticus">de Romanticus</option>
<option value="5 de Waarnemer">de Waarnemer</option>
<option value="6 de Loyalist">de Loyalist</option>
<option value="7 de Plannenmaker">de Plannenmaker</option>
<option value="8 de Leider">de Leider</option>
<option value="9 de Vredestichter">de Vredestichter</option>
</select> -->
<?php
if(isset($_POST['getdata'])){
$conn=mysql_connect('localhost','t','w');
mysql_select_db("test",$conn);
$regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";
$naam=$_POST['naam'];
$date=$_POST['date'];
//$type=$_POST['type'];
//$core=$_POST['core'];
//$management=$_POST['management'];
//$names = $tools;
//$output = preg_grep('/(Andrew|John)/i', $names);
//print_r( $output );
//
//http://webcheatsheet.com/php/regular_expressions.php#match
$test = $_POST['tools'];
$result = preg_replace('/({|:|true|}|")/', '', $test);
$test2 = preg_grep('/(^RED|^BLACK|^BLUE|^ORANGE|^GREEN|^red|^black|^blue|^orange|^green)/i', $result);
$tools = json_encode($test2);
//$tools = $_POST['tools'];
//$tools = json_encode(preg_grep('/(RED|BLACK|BLUE|ORANGE|GREEN)/i', $_POST['tools']));
//$tools = json_encode($_POST['tools']);
//$analytisch=$_POST['analytisch'];
//$eneagram=$_POST['eneagram'];
if(true == false ){
echo "<label class='err'>All fields are required</label>";
}
else{
$insert="Insert into kandidaat(naam,date,tools)
values('".$naam."','".$date."','".$tools."')";
$rs=mysql_query($insert) or die(mysql_error());
?>
<script>
<?php echo "$test2"; ?>
alert('Stop the timer!');
</script>";
<?php }
}
?>
</fieldset>
<div id="accordion" style="width:90%;">
<h3>Start...</h3>
<div>
<p class="label_checkbox_pair">
<!--<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="iCheck" value="true"><label for="certs">ISTQB2</label></div>-->
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[RED]" value="true"><label>RED</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLUE]" value="true"><label>BLUE</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLACK]" value="true"><label>BLACK</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[ORANGE]" value="true"><label>ORANGE</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[GREEN]" value="true"><label>GREEN</label></div>
</p>
</div>
<h3>Part 2</h3>
<div>
<p>
<!-- zie content website https://select2.github.io/examples.html -->
<fieldset>
<div><input type="checkbox" name="tools[RED]" value="true"><label>RED</label></div>
<div><input type="checkbox" name="tools[BLUE]" value="true"><label>BLUE</label></div>
<div><input type="checkbox" name="tools[BLACK]" value="true"><label>BLACK</label></div>
<div><input type="checkbox" name="tools[ORANGE]" value="true"><label>ORANGE</label></div>
<div><input type="checkbox" name="tools[GREEN]" value="true"><label>GREEN</label></div>
</fieldset>
</p>
</div>
</div>
<br/> <button type="submit" name="getdata" class="btn">Submit</button>
Highscores
</form>
</div>
<?php
function save(){
}
?>
<?php
function make_links_clickable($text){
return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i', '$1', $text);
}
?>
</td>
</tr>
</table>
</body>
</html>
I am devlopping an application with php and i would adding 2 buttons in one page php and i'm passing the name of each bottons to the function (POST) like this (isset($_POST['action'])) but i can't do it can you help me
<?php
$host = "localhost";
$user = "root";
$db = "reseau";
$con = #mysql_connect('localhost', 'root', '');
$select = #mysql_select_db ('reseau') ;
if (isset($_POST['action'])) {
if(isset($_POST['nom'])) $nom = htmlspecialchars(pg_escape_string($_POST['nom']));
else $nom="";
if(isset($_POST['prenom'])) $prenom = htmlspecialchars(pg_escape_string($_POST['prenom']));
else $prenom="";
if(isset($_POST['email'])) $email = $email = htmlspecialchars(pg_escape_string($_POST['email']));
else $email="";
if(isset($_POST['password'])) $password = htmlspecialchars(pg_escape_string($_POST['password']));
else $password="";
if(isset($_POST['naissance'])) $naissance = htmlspecialchars(pg_escape_string($_POST['naissance']));
else $naissance="";
if(isset($_POST['sexe'])) $sexe = htmlspecialchars(pg_escape_string($_POST['sexe']));
else $sexe="";
$query = "INSERT INTO usager(nom,prenom,email,password,naissance,sexe) VALUES ('" . $nom . "', '" . $prenom . "', '" . $email . "', '" . $password . "', '" . $naissance . "', '" . $sexe . "')";
$result = mysql_query($query);
if (!$result) {
$errormessage = mysql_error();
echo "Error with query: " . $errormessage;
exit();
}
}
else if(isset($_POST['enter'])){
if(empty($_POST['nom']) === false && empty($_POST['password']) === false){
$nom = htmlspecialchars(pg_escape_string(trim($_POST['nom'])));
$password = htmlspecialchars(pg_escape_string(trim($_POST['password'])));
$query = mysql_query("SELECT * FROM usager WHERE nom = '$nom' AND password = '$password'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output= "combinaison nom d'utilisateur/mot de passe incorrecte. réessayez";
}else{
session_start();
$_SESSION['nom']=htmlspecialchars(pg_escape_string(trim($_POST['nom'])));
$_SESSION['password']=htmlspecialchars(pg_escape_string(trim($_POST['password'])));
header("Location: index1.php");
}
}else{
$output= 'veuillez saisir tout les champs';
}
}
?>
<!DOCemail html>
<html>
<body style="background-image:url(6a00e554acca9b8834014e86765de6970d.jpg);
background-attachment : fixed;
background-position : 50% 50%;
background-size : cover;
">
<form name="nl" action="" method="POST">
<fieldset style="width: 370px; margin-top: 100px;">
<legend style= "left: 120px;">Creer un compte</legend>
<p><label for="text">Nom</label><input required placeholder="votre nom" title="Ce texte ne doit comprendre que des lettres" id="text" email="text" name="nom" style="height: 31px; margin-left: 25px;"/></p>
<p><label for="email">Prenom</label><input required placeholder="votre prenom " id="email" type="text" name="prenom"style="height: 31px; margin-left: 25px;" /></p>
<p><label for="password">Email</label><input required placeholder="votre email " id="url" type="text" name="email" style="height: 31px; margin-left: 25px;"/></p>
<p><label for="url">Mot de passe</label><input required placeholder="votre mot de passe " id="url"type="password" name="password" style="height: 31px; margin-left: 25px;"/></p>
<p><label for="url" style="width: 147px;">Date de naissance</label><input required id="birthdate" name="naissance" type="date" style="height: 31px;"/></p>
<p><label style="
width: 90px;
">Sexe</label><a>homme</a>
<input type="radio" name="sexe" value="male"
checked="checked" style="
width: 20px;
"/>
<a>femme</a>
<input type="radio" value="women" name="sexe" style="
width: 20px;
"/></p>
</fieldset>
<button type='submit' name='action' class="button" value="action" style="
padding-left: 18px;
padding-right: 18px;
padding-top: 13px;
padding-bottom: 13px;
margin-top: 0px;
border-top-width: 0px;
margin-right: 950px;
">Inscription</button>
<div id="main" class="container" style="left: 1150px;top: 270px;">
<fieldset>
<legend style="
margin-left: 65px;
">Login In</legend>
<p class="login-username">
<label for="nom">Nom:</label> <input type="text" name="nom" id="user_login" class="input" value="" size="20"
placeholder="Username" style="
height: 36px;
">
</p>
<p class="login-password">
<label for="password">Mot de passe</label> <input type="password" name="password" id="user_pass" class="input" value="" size="20" placeholder="Password" style="
height: 36px;
">
</p>
<p class="login-remember">
<label><input name="rememberme" type="checkbox" id="rememberme" value="forever"> Remember Me</label>
</p>
<p class="login-submit">
<input type='submit' name='enter' id="wp-submit" class="button-primary" value="Sign In" style="
width: 110px;
height: 36px;
"/>
</p>
</fieldset>
</div>
</form>
Any help is appreciated.
Create two submit button. Give a same name to two submit input with different value.
<input type="submit" name="btn_name" value="First Button"/>
<input type="submit" name="btn_name" value="Second Button"/>
And check it like,
if(isset($_POST) && isset($_POST['btn_name']))
{
if($_POST['btn_name'] == "First Button")
{
// first button clicked
}
else if($_POST['btn_name'] == "Second Button")
{
// second button clicked
}
}
Please add name tag in both button and check using isset() function
<input type="submit" name="btn1" value="btn1" />
<input type="submit" name="btn2" value="btn2" />
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//something posted
if (isset($_POST['btn1'])) {
// btn1
} else {
//btn2
}
}
I am working on a simple contact form written in php and have almost everything setup as I would like for it to be except right now, all validation errors are displaying in a div on the top of my form, and I would like to change the code below so they are displayed next to the form field that caused the error, but I am not sure how to accomplish this so I have come to the experts for some advise.
PHP Validation Routine
$frm_valid = new Validate();
if(isset($_POST['submit'])){
$rules=array(
array('Type'=>'Required','Var'=>$_POST['name'],'Msg'=>'Name field is required.'),
array('Type'=>'Required','Var'=>$_POST['email'],'Msg'=>'Email address field is required.'),
array('Type'=>'Email','Var'=>$_POST['email'],'Msg'=>'Your email address format is invalid.'),
array('Type'=>'Required','Var'=>$_POST['subject'],'Msg'=>'Subject field is required.'),
array('Type'=>'Required','Var'=>$_POST['message'],'Msg'=>'Message field is required.'),
);
$result = $frm_valid->Valid($rules);
if(is_array($result)){
// Print validation errors (if any)
echo('<div"><b>The form cannot be submitted until the following errors are corrected.</b><ul>');
foreach($result as $key=>$val){
echo '<li>'.$val.'</li>';
}
echo('</ul></div><br />');
}
else {
// Do something else.
}
}
Forms HTML
<form action="<? echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input type="text" name="name" value="" /> <br />
<input type="text" name="email" value="" /> <br />
<input type="text" name="subject" value="" /> <br />
<textarea name="message" cols="80" rows="7"></textarea> <br />
<input type="submit" name="submit" value="Send" />
</form>
You need to change the whole code for this!!! The structure, perhaps this way:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<ul>
<li>
<label>
<span>Name</span>
<input type="text" name="name" />
<small class="errorText"><?php echo ($_POST["name"] == "") ? "This field is required" : ""; ?></small>
</label>
</li>
<li>
<label>
<span>Email</span>
<input type="text" name="email" />
<small class="errorText"><?php echo ($_POST["email"] == "") ? "This field is required" : ""; ?></small>
</label>
</li>
<li>
<label>
<span>Subject</span>
<input type="text" name="subject" />
<small class="errorText"><?php echo ($_POST["subject"] == "") ? "This field is required" : ""; ?></small>
</label>
</li>
<li>
<label>
<span>Message</span>
<textarea name="message" cols="80" rows="7"></textarea>
<small class="errorText"><?php echo ($_POST["message"] == "") ? "This field is required" : ""; ?></small>
</label>
</li>
<li>
<input type="submit" name="submit" value="Send" />
</li>
</ul>
</form>
And the CSS for the same:
* {font-family: Segoe UI, Tahoma;}
h1 {font-weight: bold; font-size: 14pt; padding: 5px 0; margin: 5px 0; border: 1px solid #999; border-width: 1px 0;}
input[type='submit'] {padding: 5px 20px; cursor: pointer;}
ul, li {display: block; list-style: none; margin: 0; padding: 0;}
ul li {padding: 5px 0;}
ul li label span {display: block; cursor: pointer;}
ul li label .errorText {color: #f00; font-weight: bold; vertical-align: top;}
ul li label textarea {width: 300px;}
You can see a live demo here: Demo
Error Handling in PHP
Keep an error variable for each field. Say,
<?php
$error = array(
"name" => "",
"email" => "",
"subject" => "",
"message" => ""
);
?>
Update them with the errors and display them below.
<?php
if (empty()$_POST["email"])
$error["email"] = "Email is required!";
elseif (!isEmail($_POST["email"]))
$error["email"] = "Not a Valid Email!";
?>
If there are no errors, it would be empty and the user doesn't see the error message. In your Forms Code, you need to just update this way:
<small class="errorText"><?php echo $error["name"]; ?></small>
<small class="errorText"><?php echo $error["email"]; ?></small>
where in the backend, the $error["email"] would have either "This field is required" or "Not a valid email address!".
You can use the following way if your every field has a single error :
<input name='myfield'>
#if ($errors->has('myfield'))
<span style="color:red;">
{{ $errors->first('myfield') }}
</span>
#endif
I am currently building a php form utilising the jQuery iPhone style radios (found at http://devgrow.com/iphone-style-switches/). By default the radio value is set to NO in the MySQL table for every new entry, but I am having difficulty submitting the form.
How will the form be able to tell the current status of the radio button (i.e. is it set to yes or no upon submission)? Also what MySQL code would I need to use to update the value in the table? This is the code I have so far.
PHP form code
<!--- iphone checkbox --->
<script type="text/javascript">
$(document).ready( function(){
$(".cb-enable").click(function(){
var parent = $(this).parents('.switch');
$('.cb-disable',parent).removeClass('selected');
$(this).addClass('selected');
$('.checkbox',parent).attr('checked', true);
});
$(".cb-disable").click(function(){
var parent = $(this).parents('.switch');
$('.cb-enable',parent).removeClass('selected');
$(this).addClass('selected');
$('.checkbox',parent).attr('checked', false);
});
});
</script>
<style type="text/css">
.cb-enable, .cb-disable, .cb-enable span, .cb-disable span { background: url(resources/switch.gif) repeat-x; display: block; float: left; }
.cb-enable span, .cb-disable span { line-height: 30px; display: block; background-repeat: no-repeat; font-weight: bold; }
.cb-enable span { background-position: left -90px; padding: 0 10px; }
.cb-disable span { background-position: right -180px;padding: 0 10px; }
.cb-disable.selected { background-position: 0 -30px; }
.cb-disable.selected span { background-position: right -210px; color: #fff; }
.cb-enable.selected { background-position: 0 -60px; }
.cb-enable.selected span { background-position: left -150px; color: #fff; }
.switch label { cursor: pointer; }
.switch input { display: none; }
</style>
</head>
<body style="text-align:left;">
<div style="padding: 15px;">
<span class="loginfail" style="font-size:24px; font-weight: bold">Notifications</span><p>
<?php include("progress_insertcomment.php"); ?>
<?php
// Make a MySQL Connection
mysql_select_db("speedycm_data") or die(mysql_error());
$query_comment = "select * from tbl_alert order by id desc limit 1";
$comment = mysql_query($query_comment, $speedycms) or die(mysql_error());
$row_comment = mysql_fetch_assoc($comment);
$totalRows_comment = mysql_num_rows($comment);
?>
<!--- add notification --->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<span id="sprytextarea1">
<textarea id='comment' name="comment" style="height: 75px; width:330px;"><?php echo $row_comment['comment']; ?></textarea>
</span>
<p>
<button type="submit">Add</button>
<input type="hidden" name="notc" value="1"/>
</form>
<!--- notification history --->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table border="0" cellspacing="2" cellpadding="2">
<?php
if ( $row_comment == 0 ) {
echo "<span style='font-size: 11px;'>No current alerts.</span>";
} else {
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM tbl_alert ORDER BY id DESC")
or die(mysql_error());
while($rows=mysql_fetch_array($result)){ ?>
<tr>
<td>
<?php
echo "<div class='bubble'><div class='pimped'>
<blockquote>" . $rows['comment'] . "
</blockquote></div>
<cite><strong>" . $rows['user'] . "</strong> # " . $rows['date'] . "</cite>
<span style='font-size: 10px;'>
<p>
<a href='editalert.php?id=". $rows['id'] ."' class='form' >Edit</a> • <a href='deletealert.php?id=". $rows['id'] ."' class='form'>Delete</a>
</span>
</div>
";
?>
</td>
<td valign="top" align="center"><div style="padding-left: 30px;"><span style="font-size: 10px;">Completed?</span>
<p class="field switch">
<!--- determine status of notification --->
<?php
$status = $rows['status'];
if ( $status == yes ) {
echo '<input type="radio" id="radio1" name="'.$rows['id'].'" value="no" checked/>
<input type="radio" id="radio2" name="'.$rows['id'].'" value="yes"/>
<label for="radio1" class="cb-enable selected"><span>Yes</span></label>
<label for="radio2" class="cb-disable"><span>No</span></label>';
} else {
echo '<input type="radio" id="radio1" name="'.$rows['id'].'" value="yes"/>
<input type="radio" id="radio2" name="'.$rows['id'].'" value="no" checked/>
<label for="radio1" class="cb-enable"><span>Yes</span></label>
<label for="radio2" class="cb-disable selected"><span>No</span></label>';
}
?>
</p>
</div></td>
</tr>
<tr>
<td></td>
<td align="center"><div style="padding-left: 30px;">
<button type="submit">Update</button>
<input type="hidden" name="notc2" value="1"/>
</div></td>
</tr>
<?php
}
}
?>
</table>
</form>
</div>
code to submit form
<?php
// 6) update notifications
if (array_key_exists('notc2',$_POST)) {
echo "<p style='font-size: 12px;'>Thank you. The notifications have been updated successfully.</p>";
echo "<span style='font-size: 12px;'>
<a onClick=\"history.go(-1)\" class='form'>Return</a>
<p></span>
";
exit;
};
?>
The information will be present within $_POST['<id>'] where <id> corresponds to the row in tbl_alerts as given in your php form:
echo '<input type="radio" id="radio1" name="'.$rows['id'].'" value="no" checked/>
<input type="radio" id="radio2" name="'.$rows['id'].'" value="yes"/>
(emphasis added)
You can (and should) verify that by adding a var_dump($_POST) up the top of your processing script.
It will be hard for your processing script to know the id value though so what you probably want is name the radio as some other name, and then add a hidden form field that will store the id.
ex. your radio buttons would appear:
<input type="radio" id="radio1" name="status" value="no" checked/>
<input type="radio" id="radio2" name="status" value="yes"/>
and then somewhere in your code you have:
echo '<input type="hidden" name="statusid" value="'.$rows['id'].'"/>';
That way, the radio button value will be in $_POST['status'] and the id of the row will be in $_POST['statusid']