PHP Focus on input - php

I am trying to create a PHP validation FORM.
Validation errors are displaying correctly for me every time. My only problems is that I am not able to set the focus on the input with error if an error came.
For example, I am using $rut_error, $first_name_error, $last_name_error, $email_error, $address_error and I want to set focus on the corresponding input if any error came.
I tried using javascript but I am not cleared where should I put that code, Could anyone guide me how to solve it? Can I fix this only with PHP? Please help.
I tried entering here but no success:
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
My code is below:
addStudent.php
<html>
<head>
<title>Add Client</title>
</head>
<body>
Show Client
<?php include('form_processStudent.php'); ?>
<div id="divAgenda">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post" name = "registration">
<fieldset>
<span class="error"><?= $rut_error ?></span><br>
<input placeholder="Rut..." id="rut" type="text" name="rut" value="<?= $rut ?>" tabindex="1" size="8" maxlength="8"> - <input type="text" name="dv" value="<?= $dv ?>" size="1" tabindex="2" maxlength="1"> Ejemplo: 12345678-1<br>
</fieldset>
<fieldset>
<span class="error"><?= $first_name_error ?></span><br>
<input placeholder="Primer Nombre..." id="first_name" type="text" id="first_name" name="first_name" value="<?= $first_name ?>" maxlength="50" tabindex="3"><br>
</fieldset>
<fieldset>
<span class="error"><?= $last_name_error ?></span><br>
<input placeholder="Segundo Nombre..." id="last_name" type="text" id="last_name" name="last_name" value="<?= $last_name ?>" maxlength="50" tabindex="4"><br>
</fieldset>
<fieldset>
<span class="error"><?= $email_error ?></span><br>
<input placeholder="Correo Electrónico..." id="email" type="text" name="email" value="<?= $email ?>" maxlength="100" tabindex="5"><br>
</fieldset>
<fieldset>
<span class="error"><?= $address_error ?></span><br>
<input placeholder="Dirección..." id="address" type="text" name="address" value="<?= $address ?>" maxlength="200" tabindex="5"><br>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>
</form>
</body>
</html>
form_processStudent.php
<?php
// define variables and set to empty values
echo"<script>
document.registration.last_name.focus();
return false;
</script>";
$rut_error = $first_name_error = $last_name_error = $email_error = $address_error = "";
$rut = $dv = $first_name = $last_name = $email = $address = "";
if(isset($_POST['submit']))
{
//RUT Validation
$rut = test_input($_POST["rut"]);
$dv = ($_POST["dv"]);
if ( empty($_POST["rut"]))
{
$rut_error = "RUT is required";
}
else if ( $dv=='' )
{
$rut_error = "Verification digit is required";
}
else if (!is_numeric($rut))
{
$rut_error = "Entered RUT is not numeric";
}
else if (!((strlen($rut) == 7) or (strlen($rut) == 8)))
{
$rut_error = "Number of digits of RUT not valid";
}
else
{
$x = 2; $s = 0; $dv2 = 0;
for($i = (strlen($rut) - 1); $i >= 0; $i--)
{
if($x > 7)
$x = 2;
$s += ($rut[$i] * $x);
$x++;
}
$dv2=11-($s % 11);
if($dv2 == 10)
$dv2 = 'K';
if($dv2 == 11)
$dv2 = '0';
if($dv2 == $dv)
{
//echo "<br>". "rut={" . $rut . "}";
//echo "<br>". "dv ={" . $dv . "}";
}
else
$rut_error = "invalid RUT";
}
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
else
{
if ($rut_error == '')
{
$first_name = test_input($_POST["first_name"]);
//echo "<br>". "first_name={" . $first_name . "}";
}
}
//Last name Validation
if (empty($_POST["last_name"]) and $rut_error == '' and $first_name_error == '')
{
$last_name_error = "Second name is required";
echo "<script>function validateform()
{
document.registration.last_name.focus();
return false;
}
</script>";
}
else
{
if ($rut_error == '' and $first_name_error == '')
{
$last_name = test_input($_POST["last_name"]);
//echo "<br>". "last_name={" . $last_name . "}";
}
}
//Email Validation
if (empty($_POST["email"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Email is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email = test_input($_POST["email"]);
//echo "<br>". "email={" . $email . "}";
// check if e-mail address is well-formed
if ((!filter_var($email, FILTER_VALIDATE_EMAIL)) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Invalid email";
}
}
}
//Adress Validation
if (empty($_POST["address"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address_error = "Address is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address = test_input($_POST["address"]);
//echo "<br>". "address={" . $address . "}";
}
}
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '' and $address_error == '')
{
//echo "<br>". "Dentro de IF";echo "<br>";
require_once('mysqli_connect.php');
$query = "INSERT INTO students (rut, dv, first_name, last_name, email, address) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ssssss", $rut, $dv, $first_name, $last_name, $email, $address);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo 'affected_rows=<' . $affected_rows . '>';
if($affected_rows == 1)
{
$rut = $dv = $first_name = $last_name = $email = $address = '';
echo "<br>"."Client Entered";
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
else
{
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
getStudentInfo.php
Add Client
<?php
// Get a connection for the database
require_once('mysqli_connect.php');
// Create a query for the database
$query = "SELECT serie, rut, dv, first_name, last_name, email, address FROM students ORDER BY serie desc";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response)
{
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Serie </b></td>
<td align="left"><b>Rut </b></td>
<td align="left"><b>Dígito Verificador </b></td>
<td align="left"><b>Primer Nombre </b></td>
<td align="left"><b>Segundo Nombre </b></td>
<td align="left"><b>Email </b></td>
<td align="left"><b>Dirección </b></td>
</tr>';
// mysqli_fetch_array will return a row of data from the query
// until no further data is available
while($row = mysqli_fetch_array($response))
{
echo '<tr><td align="left">' . $row['serie'] . '</td>
<td align="left">' . $row['rut'] . '</td>
<td align="left">' . $row['dv'] . '</dv>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['email'] . '</td>
<td align="left">' . $row['address'] . '</td>'
;
echo '</tr>';
}
echo '</table>';
}
else
{
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
// Close connection to the database
mysqli_close($dbc);
?>
mysqli_connect.php
<?php
// Defined as constants so that they can't be changed
DEFINE ('DB_USER', 'studentweb');
DEFINE ('DB_PASSWORD', '123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'dbTest');
// $dbc will contain a resource link to the database
// # keeps the error from showing in the browser
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' . mysqli_connect_error());
//echo "Connected...\n\n";
?>

You can do it via javascript.
You put a script that would work once the page is fully loaded.
The script will checkout the content of each <span class="error">. If some non empty one is found, it shall put the focus on it.
In your html:
<body>
...
<script type="text/javascript">
window.onload = function(){
var errors = document.querySelectorAll('.error');
for(var i = 0, l = errors.length; i < l; i++){
var error = errors[i],
shouldForcus = error.textContent.trim().length !== 0;
if(shouldFocus){
var input = error.parentNode.querySelector('input');
input.focus();
break;
}
}
}
</script>
</body>

Related

PHP won't insert data to Mysql database - No error thrown

Hi so I can't seem to find any help on this topic because there is no error being thrown. I am trying to insert records to a database via php using mysqli_query but after the re-direct no changes are made. I have three files I am working with, index.php, conn.php and new.php. index.php and new.php are located in the same folder but conn.php is one directory below.
index.php:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" >
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Khula" rel="stylesheet">
</head>
<script>
$(function()
{
$('.error').fadeOut(10000);
});
</script>
<body>
<header>
<img src="images/logo.png">
<p>The reliable bus company</p>
</header>
<div class="wrapper">
<div class="container">
<div class="titletxt">
<h4>Drivers</h4>
</div>
<?php
include '../conn.php';
mysqli_query($conn, "SET NAMES utf8");
$result = mysqli_query($conn, "SELECT * FROM tbl_employee");
echo "
<div class='table_content'>
<table align='center'>
<tr>
<th>Employee ID</th>
<th>Title</th>
<th>Name</th>
<th>Address</th>
<th>Contact Number</th>
<th>Job Position</th>
<th>Gender</th>
<th>DOB</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['employeeID'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['contactNum'] . "</td>";
echo "<td>" . $row['position'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['DOB'] . "</td>";
echo "</tr>";
}
echo "</table></div>";
?>
<!-- Record Insert -->
<br>
<div class="titletxt">
<h4>Insert a Record</h4>
</div>
<h3 style="font-weight: 400; margin-left: 5px;">New Employee</h3>
<form class="insert_form" action="new.php" method="post" name="insert_form">
<label>Title: </label>
<input type="text" name="title" required><br>
<span class="error"><?php echo $titleErr ?></span>
<br>
<label>Name: </label>
<input type="text" name="name" required> <br>
<span class="error"><?php echo $nameErr ?></span>
<br>
<label>Address:</label>
<input type="text" name="address" required><br>
<span class="error"><?php echo $addressErr ?></span>
<br>
<label>Contact Number</label>
<input type="text" name="contactNum" required><br>
<span class="error"><?php echo $contactErr ?></span>
<br>
<label>Job Position</label>
<input type="text" name="position" required><br>
<span class="error"><?php echo $positionErr ?></span>
<br>
<label>Gender: </label>
<input type="radio" name="gender" value="male" required> Male
<input type="radio" name="gender" value="female" required> Female<br>
<span class="error"><?php echo $genderErr ?></span>
<br>
<label>DOB: </label>
<input style="width: 60px;" type="text" name="DOB_year" required>YYYY
<input style="width: 30px;" type="text" name="DOB_months" required>MM
<input type="text" name="DOB_day" style="width: 30px" required>DD<br>
<span class="error"><?php echo $DOBErr ?></span>
<br>
<input type="submit" Value="Insert Entry">
</form>
</div>
</div>
</body>
</html>
conn.php:
<?php
$server = "localhost";
$user = "root";
$password = "";
$db = "bus_db";
global $conn;
$conn = mysqli_connect($server, $user, $password, $db);
if(mysqli_connect_errno())
{
echo "Mysql Error has occured" . mysqli_connect_error;
}
else if(!mysqli_connect_errno())
{
echo "<connection>Connection Established</connection>";
}
function close_connection()
{
global $conn;
mysqli_close($conn);
}
$title = $name = $address = $contact = $position = $gender = $DOB = "";
$titleErr = $nameErr = $addressErr = $contactErr = $positionErr = $genderErr = $DOBErr = "";
mysqli_query($conn, "SET NAMES utf8");
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["title"]))
{
$titleErr = "Title is Required";
}else{
$title = input($_POST["title"]);
}
if (empty($_POST["name"]))
{
$nameErr = "Name is Required";
}else
{
$name = input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid Name";
}
}
if (empty($_POST["address"]))
{
$addressErr = "Address is Required";
}else{
$address = input($_POST["address"]);
}
if (empty($_POST["contactNum"]))
{
$contactErr = "Contact Number is required ";
}else{
$contact = input($_POST["contactNum"]);
$regex = "^([0-9]{10,11})$^";
if (!preg_match($regex, $contact)) {
$contactErr = "Invalid Phone Number";
}
}
if(empty($_POST["position"]))
{
$positionErr = "Position is required";
}else{
$position = input($_POST["position"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is Required";
}else{
$gender = input($_POST["gender"]);
}
if (empty($_POST["DOB_year"]) || empty($_POST["DOB_months"]) || empty($_POST["DOB_day"]))
{
$DOBErr = "Invalid entry for date of birth";
}else
{
$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
global $conn;
mysqli_query($conn, "INSERT INTO tbl_employee VALUES(null, '" .$p_title."', '".$p_name."', '".$p_address."', '".$p_contact."', '".$p_position."', '".$p_gender."', '".$p_DOB."')");
}
?>
new.php:
<?php
include '../conn.php';
insert_records($title, $name, $address, $contact, $position, $gender, $DOB);
header( 'Location:index.php');
close_connection();
?>
I would appreciate any, thanks
You should edit your insert_records() to give you feedback if mysqli_query fails.
function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
global $conn;
$result = mysqli_query($conn, 'some query') or die('Query failed: ' . mysqli_error($conn));
return $result;
}
and read about how you can prevent MySQL injection here: How can I prevent SQL injection in PHP?
edit:
$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
in php '+' is used to do calculations. if you want to concatenate strings use '.'
$DOB = input($_POST["DOB_year"] . "/" . $_POST["DOB_months"] . "/" . $_POST["DOB_day"]);

php form 2 step confirmation

i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>

php string validation not working

So I have the following code:
<body>
<?php
$firstname = $lastname = $phone = $phone = $email = $date = $code = "";
$firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
$check = 0;
$str = "abcdefghijklmnopqrstuvwxyz";
$rand1 = $str[rand(0, strlen($str) - 1)];
$rand2 = $str[rand(0, strlen($str) - 1)];
$rand3 = $str[rand(0, strlen($str) - 1)];
$rand4 = $str[rand(0, strlen($str) - 1)];
$rand5 = $str[rand(0, strlen($str) - 1)];
$final = $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["ffirstname"])){
$firstnameerr = "First Name is empty!";
$check = 1;
} else {
$firstname = testInput($_POST['ffirstname']);
$check = 0;
if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
$firstnameerr = "This is not a valid name!";
$check = 1;
}
}
if (empty($_POST["flastname"])){
$lastnameerr = "Last Name is empty!";
$check = 1;
} else {
$lastname = testInput($_POST['flastname']);
$cheek = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
$lastnameerr = "This is not a valid name";
$check = 1;
}
}
if (empty($_POST["fphone"])){
$phoneerr = "Phone field is empty!";
$check = 1;
}else {
$phone = testInput($_POST['fphone']);
if(!is_numeric($phone)){
$phoneerr = "Phone number is not a number";
$check = 1;
}
}
if (empty($_POST["femail"])){
$emailerr = "E-mail field is empty!";
} else {
$email = testInput($_POST['femail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "E-mail is not valid";
$check = 1;
}
}
if (empty($_POST["fdate"])){
$dateerr = "No date selected!";
$check = 1;
} else {
$date = testInput($_POST['fdate']);
}
if (empty($_POST["fcode"])){
$codeerr = "There is no code!";
$check = 1;
} else {
$code = $_POST["fcode"];
if ($code !== $final){
$codeerr = "The code is wrong";
$check = 1;
}
}
if ($check == 0) {
$host = "localhost";
$user = "root";
$pass = "";
$db = "myfirstdb";
$connect = new mysqli($host,$user,$pass,$db);
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connected successfully!";
}
$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
}
}
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="header">
<img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
<div id="top"><h1 id="first">Welcome to my website</h1></div>
</div>
<div id="section">
<div id="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
</div>
<div id="article">
<h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="namer">First Name</p><br>
<input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
<p class="namer">Last Name</p><br>
<input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
<p class="namer">Phone Number</p><br>
<input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
<p class="namer">E-mail</p><br>
<input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
<p class="namer">Date</p><br>
<input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
<p class="namer">Enter the Captcha code!</p><br>
<h1><?php echo $final?></h1><br>
<input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
<input type="submit" name="fsubmit" value="Submit">
</form>
</div>
</div>
My problem is with the code a.k.a in the if that uses $code and $final to check wheather it's a human or not. Now whenever i write the exact same thing as in the $final variable the program thinks it's not the same so i get the $codeerr. Can someone please help me fix it?
Ok, I added little changes to your code, and I think it should work now.
<?php
session_start();
?>
<body>
<?php
function generateCode() {
$str = "abcdefghijklmnopqrstuvwxyz";
$rand1 = $str[rand(0, strlen($str) - 1)];
$rand2 = $str[rand(0, strlen($str) - 1)];
$rand3 = $str[rand(0, strlen($str) - 1)];
$rand4 = $str[rand(0, strlen($str) - 1)];
$rand5 = $str[rand(0, strlen($str) - 1)];
return $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
}
$firstname = $lastname = $phone = $phone = $email = $date = $code = "";
$firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
$check = 0;
if(!isset($_SESSION['final'])) {
$_SESSION['final'] = generateCode();
}
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["ffirstname"])){
$firstnameerr = "First Name is empty!";
$check = 1;
} else {
$firstname = testInput($_POST['ffirstname']);
$check = 0;
if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
$firstnameerr = "This is not a valid name!";
$check = 1;
}
}
if (empty($_POST["flastname"])){
$lastnameerr = "Last Name is empty!";
$check = 1;
} else {
$lastname = testInput($_POST['flastname']);
$cheek = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
$lastnameerr = "This is not a valid name";
$check = 1;
}
}
if (empty($_POST["fphone"])){
$phoneerr = "Phone field is empty!";
$check = 1;
}else {
$phone = testInput($_POST['fphone']);
if(!is_numeric($phone)){
$phoneerr = "Phone number is not a number";
$check = 1;
}
}
if (empty($_POST["femail"])){
$emailerr = "E-mail field is empty!";
} else {
$email = testInput($_POST['femail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "E-mail is not valid";
$check = 1;
}
}
if (empty($_POST["fdate"])){
$dateerr = "No date selected!";
$check = 1;
} else {
$date = testInput($_POST['fdate']);
}
if (empty($_POST["fcode"])){
$codeerr = "There is no code!";
$check = 1;
} else {
$code = $_POST["fcode"];
if ($code !== $_SESSION['final']){
$codeerr = "The code is wrong";
$check = 1;
}
}
if ($check == 0) {
$host = "localhost";
$user = "root";
$pass = "";
$db = "myfirstdb";
$connect = new mysqli($host,$user,$pass,$db);
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connected successfully!";
}
$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
}
}
if($check == 1) {
$_SESSION['final'] = generateCode();
}
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="header">
<img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
<div id="top"><h1 id="first">Welcome to my website</h1></div>
</div>
<div id="section">
<div id="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
</div>
<div id="article">
<h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="namer">First Name</p><br>
<input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
<p class="namer">Last Name</p><br>
<input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
<p class="namer">Phone Number</p><br>
<input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
<p class="namer">E-mail</p><br>
<input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
<p class="namer">Date</p><br>
<input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
<p class="namer">Enter the Captcha code!</p><br>
<h1><?php echo $_SESSION['final']?></h1><br>
<input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
<input type="submit" name="fsubmit" value="Submit">
</form>
</div>
</div>
You must save $final code in $_SESSION for example, because after submit of the form the code for generating $final will get executed and $final will get new value different from the rendered code before submit.

Slashes automatically added to text boxes php

I have been racking my brain to understand why there are slashes ("/") in every one of by textboxes on my page when I run this php script. Everything on the page works fine. I have tried everything but they're just there. Here my whole code below. Thanks for any help!
function validateInput($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else if (!preg_match('/[^A-Za-z]/', $data) == 0){
echo "\"$fieldName\" can only contain letters.<br />\n";
++$error;
$retval = "";
} else {
$retval = trim($stripslashes($data));
}
return ($retval);
}
function validateAddress($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else if (!preg_match('/[^0-9A-Za-z]/', $data)){
echo "\"$fieldName\" can only contain letters or numbers.<br />\n";
++$error;
$retval = "";
} else {
$retval = trim(stripslashes($data));
}
return ($retval);
}
function validateNumber($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else if (!is_numeric($data)){
echo "\"$fieldName\" must contain only numbers.<br />";
++$error;
$retval = "";
} else if (strlen($data) != 10){
echo "\"$fieldName\" must be 10 numbers long.<br />";
++$error;
$retval = "";
} else {
$retval = trim(stripslashes($data));
}
return ($retval);
}
function validateEmail($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else {
$retval = trim(stripslashes($input));
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\.[a-z]{2,})$/i";
if (preg_match($pattern, $retval) == 0){
echo "\"$fieldName\" is not a valid email address.<br />\n";
++$error;
}
}
return($retval);
}
function displayForm($name, $email, $address, $phone){
include("header.html");
?>
<div class="center">
<form name="contact_us" action="contact_us.php" method="post">
<p>Your Name: <input type="text" name="name" value=<?php echo $name; ?> /></p>
<p>Your Email: <input type="text" name="email" value=<?php echo $email; ?> /></p>
<p>Your Address: <input type="text" name="address" value=<?php echo $address; ?> /></p>
<p>Your Phone Number: <input type="text" name="phone" value=<?php echo $phone;?> /></p>
<p><input type="submit" name="Submit" value="Send" />
<input type="reset" value="Clear"/>
</form>
</div>
<?php
include("footer.html");
}
$showForm = TRUE;
$error = 0;
$name = "";
$email = "";
$address = "";
$phone = "";
if (isset($_POST['Submit'])){
$name = validateInput($_POST['name'], "Name");
$email = validateEmail($_POST['email'], "Email");
$address = validateAddress($_POST['address'], "Address");
$phone = validateNumber($_POST['phone'], "Phone");
if ($error == 0)
$showForm = FALSE;
else
$showForm = TRUE;
}
if ($showForm == TRUE){
if ($error > 0)
echo "<p>Please re-enter the form information below.<br/>\n";
displayForm($name, $email, $address, $phone);
} else {
echo "Your contact information has been recorded. Thank you!";
}
?>
You have to quote your value attributes in these lines:
<input type="text" name="name" value=<?php echo $name; ?> />
If $name is empty, which is true by default, your code reduces to
<input type="text" name="name" value=/ >
So your input boxes are filled with a / by default. To fix this error (and avoid other possible errors), quote your $name:
<input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>" />
Notice that I also called htmlspecialchars to prevent XSS.
PHP runs addslashes() on all GET, POST, and COOKIE data by default.

PHP/HTML form processing

The assignment is to create an html form where the user enters the required information, and process the form data via PHP to display the output using $_post method. I can't seem to get the output right, it just basically displays the php code that I wrote. any insight is greatly appreciated
Note: The html code is lengthy, but I'm sure it's correct. My problem is with the PHP(next) code.
the following is the output:
0){ $Name = trim($_POST['name']); $adr = trim($_POST['address']); $City = trim($_POST['city']); $state = trim($_POST['state']); $zip = trim($_POST['zip']); $phone = trim($_POST['phone']); $email = trim($_POST['email']); $err = array(); if($Name == ''){ $err[] = "Please enter your name"; } if($adr == ''){ $err[] = "Please enter your address"; } if($City == ''){ $err[] = "Please enter your city"; } if($state == ''){ $err[] = "Please enter your State"; } if($zip == ''){ $err[] = "Please enter your zip"; } if($phone == ''){ $err[] = "Please enter your phone number"; } if($email == ''){ $err[] = "Please enter your email"; } if(count($err) > 0){ foreach($err as $value){ echo"$value
"; } echo " Go Back"; } else{ //header("Location:HTMLform.html"); echo "Name: " . $_POST["name"]; echo "Address: " . $_POST["address"] ; echo "City: " . $_POST["city"] ; echo "State: " . $_POST["state"]; echo "Zip: " . $_POST["zip"]; echo "Phone: " . $_POST["phone"]; echo "Email: " . $_POST["email"]; } } ?>
page 1 (HTML FORM)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Coffee Order</title>
</head>
<body><h1>The Coffee House</h1>
<div>
<div><h3>Order Form</h3></div>
<form name='frmInput' action="process.php" method="post">
<table><tr><td>Coffee:</td>
<td><select name="coffeeCode" id="Coffee">
<option value="">Select Coffee:</option><option value="bv">Boca Villa ($7.99/lb)
</option>
<option value="sbr">South Beach Rhythm ($8.99/lb)</option>
<option value="pp">Pumpkin Paradise ($8.99/lb)</option>
<option value="ss">Sumatran Sunset ($9.99/lb)</option>
<option value="bb">Bali Batur ($10.95/lb)</option>
<option value="dd">Double Dark ($9.95/lb)</option></select></td></tr>
<tr><td>
Type:</td>
<td>
<input type="radio" name="coffeeType" value="caf">Regular<br/>
<input type="radio" name="coffeeType" value="decaf">Decaffeinated
</td>
</tr>
<tr>
<td>Quantity (in pounds):</td>
<td>
<input type="text" name="quantity" maxlength="3" size="3" id="Quantity">
</td>
</tr>
<tr>
<td>Name:</td>
<td>
<input type="text" name="name" id="Name">
</td>
</tr>
<tr>
<td>E-mail address:</td>
<td>
<input type="text" name="email" id="Email">
</td>
</tr>
<tr>
<td>Telephone #:</td>
<td>
<input type="text" name="phone" maxlength="14" size="14" id="Telephone">
</td>
</tr>
<tr>
<td>Address:</td>
<td>
<input type="text" name="address" id="Address">
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input type="text" name="city" id="City">
</td>
</tr>
<tr>
<td>State:</td>
<td>
<input type="text" name="state" maxlength="2" size="2"
style="text-transform: uppercase" id="State">
</td>
</tr>
<tr>
<td>Zip:</td>
<td>
<input type="text" name="zip" maxlength="10" size="10" id="Zip">
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td><td><input type="reset"></td>
</tr>
</table>
</form></div></body>
</html>
php code:
<?php
if (count($_POST) > 0){
$Name = trim($_POST['name']);
$adr = trim($_POST['address']);
$City = trim($_POST['city']);
$state = trim($_POST['state']);
$zip = trim($_POST['zip']);
$phone = trim($_POST['phone']);
$email = trim($_POST['email']);
$err = array();
if($Name == ''){
$err[] = "Please enter your name";
}
if($adr == ''){
$err[] = "Please enter your address";
}
if($City == ''){
$err[] = "Please enter your city";
}
if($state == ''){
$err[] = "Please enter your State";
}
if($zip == ''){
$err[] = "Please enter your zip";
}
if($phone == ''){
$err[] = "Please enter your phone number";
}
if($email == ''){
$err[] = "Please enter your email";
}
if(count($err) > 0){
foreach($err as $value){
echo"$value<br/>";
}
echo "<a href='HTMLform.html'> Go Back</a>";
}
else{
//header("Location:HTMLform.html");
echo "Name: " . $_POST["name"];
echo "Address: " . $_POST["address"] ;
echo "City: " . $_POST["city"] ;
echo "State: " . $_POST["state"];
echo "Zip: " . $_POST["zip"];
echo "Phone: " . $_POST["phone"];
echo "Email: " . $_POST["email"];
}
}
?>
You have some errors in your code.
There is a space between <? tag and php in line 1. Remove that
There is no closing curly brace for this , if (count($_POST) > 0) {. Add a closing curly brace before the ending ?> tag.
You have the name field of telephone set to 'phone'.
So find all lines having this
$_POST['telephone']
and change it to
$_POST['phone']
Also, If you want to see the results, comment out
header('Location:HTMLForm.html');
PHP file are saved with .php extension and has an opening of
PHP code should be at the top of the page, before any HTML tag
Instead of using $variable == '' to check if it's empty, use function called empty($variable) that return true if empty
You are doing a redirect in the first line of the else statement, so the rest of the code won't be executed, therefore the echo part will never be reached. Put this header("Location:HTMLform.html"); as the last statement in the else scope
old
// is this suppose to be an array?
$err = array();
if($_POST['name'] == null){
array_push($err,'error stuff stuff stuff');
}
print_r($err);
// if not array
$err = '';
if($_POST['name'] == null){
$err.= 'error stuff stuff stuff';
}
Also, What are you trimming from the post?

Categories