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"]);
Related
i'm learning php since a week from now, and one of my project is to make a form that adapt fields about a url token.
For example: if the user is a student token will be index.php?token=e3
the user is a professionnal will be index.php?token=p4
i'm realy happy because everything is working, except the last part.. the POST of the user informations in my db called "test" which as a single table called form and i the db got good settings, the table is well designed with int-varchars, anything that can handle the datas.
i would like to atleast make it work for e3 then i'll be able to adapt for the others, that's why i give you an example of what i did since now, maybe i'm missing something important but i got no php errors, the datas are not sending when i press send button and the page refresh as index.php
if you guys got an idea, you don't need to tell me realy how to do, i just need someone better than me that could tell me "well you should look at sessions" or something else that is wrong because i have no clue to debug i'm stuck since yesterday on this problem.
Here is my code remember if you want to make it appear clearly you need to specify the token "?token=e3"
thank you in advance everyone who'll help me:
<?php
session_start();
$connectionSql = array(
"hote" => "localhost",
"base" => "test",
"user" => "root",
"pwd" => "",
);
try {
$db = new PDO("mysql:host=" . $connectionSql["hote"] . ";dbname=" . $connectionSql["base"],
$connectionSql["user"], $connectionSql["pwd"]);
/*var_dump($db);*/
$db->exec("set names utf8");
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
$url = substr($getWholeUrl , -2);
if ($url=="e3" && isset($_POST['send'])) {
if(!empty($_POST['gender']) AND !empty($_POST['name']) AND
!empty($_POST['firstname']) AND !empty($_POST['mail']) AND
!empty($_POST['phone']) AND !empty($_POST['speciality']) AND
$_POST['speciality'] != "Votre spécialité" AND !empty($_POST['year']) AND
!empty($_POST['birthday']) AND !empty($_POST['school']) AND
!empty($_POST['zipcode']) AND !empty($_FILES['attachment']) AND
!empty($_FILES['pi']))
{
$gender = $_POST['gender'];
$name = htmlspecialchars($_POST['name']);
$firstname = htmlspecialchars($_POST['firstname']);
$mail = htmlspecialchars($_POST['mail']);
$phone = $_POST['phone'];
$speciality = $_POST['speciality'];
$year = $_POST['year'];
$birthday = $_POST['birthday'];
$school = htmlspecialchars($_POST['school']);
$zipcode = htmlspecialchars($_POST['zipcode']);
$filename = $_FILES['attachment']['name'];
$idname = $_FILES['pi']['name'];
$reqmail= $db->prepare("SELECT * FROM `form` WHERE mail = ?");
$reqmail->execute(array($mail));
$mailexist = $reqmail->rowCount();
if($mailexist == 0) {
if (filter_var($mail, FILTER_VALIDATE_mail)) {
if (is_numeric($phone) == true && preg_match('/^\d{10}$/', $phone)) {
if (is_numeric($year) == true) {
if(!empty($_FILES['attachment']['name']) && !empty($_FILES['pi']['name'])){
if ($_FILES['attachment']['error'] == 0 && $_FILES['attachment']['size'] < 2097152 && $_FILES['pi']['error'] == 0 && $_FILES['pi']['size'] < 2097152) {
$extension = pathinfo($filename);
if ($extension["extension"] == "jpg" || $extension["extension"] == "png" || $extension["extension"] == "pdf") {
$extensionid = pathinfo($idname);
if($extensionid["extension"] == 'jpg' || $extensionid['extension'] == "png" || $extensionid['extension'] == "pdf") {
$req = $db->query('SELECT MAX(id) FROM form');
$res = $req->fetchColumn();
$res += 1;
if(!is_dir('img/')) {
mkdir('img/', 0755);
}
if(!is_dir('img/img' . $res . '/')){
mkdir('img/img' . $res . '/', 0755);
}
move_uploaded_file($_FILES['attachment']['tmp_name'], 'img/img' . $res . '/' . $res . $filename);
move_uploaded_file($_FILES['pi']['tmp_name'], 'img/img' . $res . '/' . $res . 'id' . $idname);
$require = $db->prepare("INSERT INTO `form` (`gender`, `name`, `firstname`, `mail`, `phone`, `speciality`, `year`, `birthday`, `school`, `zipcode`, `attachment`, `idcard`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$require->execute(array($gender, $name, $firstname, $mail, $phone, $speciality, $year, $birthday, $school, $zipcode, $res . $filename, $res . $idname));
$succes = "Form as been sent !";
}else{
$erreur = "idcard's extension isn't admitted.";
}
}else{
$erreur = "attachment's extension isn't admitted.";
}
}else{
$erreur = "File too big - Max 2Mo";
}
}else{
$erreur = "Please join the two required attached files.";
}
} else {
$erreur = $year . " isn't a valable year !";
}
} else {
$erreur = $phone . " isn't a right phone number !";
}
}else{
$erreur = "invalid mail";
}
}else{
$erreur = "mail already exists !";
}
}else{
$erreur = "please complete all the fields !";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="icon" type="image/icon-x" href="images/favicon.ico">
</head>
<body>
<div class="background">
<div align="center">
<h1 class="logo">
<img src="images/logo.png" alt="logo">
</h1>
<?php
if(isset($succes))
{
echo "<div class=\"alert alert-success\">".$succes."</div>";
}
if(isset($erreur))
{
echo "<div class=\"alert alert-danger\">".$erreur."</div>";
}
?>
<div class="image">
<section>
<form method="post" action="index.php" enctype="multipart/form-data">
<div class="radioclass">
<input type="radio" name="gender" id="gender" value="1"/>
<label class="btn" for="gender">Woman</label>
<input type="radio" name="gender" id="gender" value="2"/>
<label class="btn" for="gender">Man</label>
<input type="radio" name="gender" id="gender" value="3"/>
<label class="btn" for="gender">Unicorn</label>
</div>
<div class="user-input-wrp">
<div class="user-input-name">
<input type="text" name="name" id="name"/ required>
<span class="name">name</span>
</div>
<div class="user-input-surname">
<input type="text" name="firstname" id="firstname"/ required>
<span class="firstname">firstname</span>
</div>
<div class="user-input-mail">
<input type="mail" name="mail" id="mail"/ required>
<span class="mail">mail</span>
</div>
<div class="user-input-mobile">
<input type="tel" name="phone" id="phone" required>
<span class="phone">phone</span>
</div>
<?php
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='e3'){
$listespeciality = array("your speciality",
"Fitness",
"Bodybuilding",
"Flower-eating");
echo "<select name=\"speciality\" id=\"speciality\">";
foreach ($listespeciality as $indice => $speciality) {
echo "<option value=\"";
echo $speciality;
echo "\">";
echo $speciality;
echo "</option>";
}
echo "</select>";
}
else {
echo "<div class=\"user-input-seccia\">"."<input type=\"text\" name=\"secteur\" id=\"secteur\">"."<span class=\"secteur\">activity</span>"."</div>";
}
?>
<div class="user-input-year">
<input type="text" name="year" id="year" required>
<span class="year">Year of activity</span>
</div>
<?php
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='e3'){
echo "
<div class=\"user-input-building\">
<input type=\"text\" name=\"school\" id=\"school\" required>
<span class=\"school\">school</span>
</div>";}
else if(substr($getWholeUrl , -2)=='p4' || substr($getWholeUrl , -2)=='o1') {
echo "
<div class=\"user-input-siret\">
<input maxlength=\"14\" type=\"text\" name=\"idcode\" id=\"idcode\" required>
<span class=\"siret\">identity code</span>
</div>";} ?>
<?php
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='a2') {
$listmedia = array("Blog",
"Facebook",
"Instagram",
"Own website");
echo "<select name=\"media\" id=\"media\">";
foreach ($listmedia as $indice => $media) {
echo "<option value=\"";
echo $media;
echo "\">";
echo $media;
echo "</option>";
}
echo "</select>";
} ?>
<?php $getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='o1' || substr($getWholeUrl , -2)=='p4'){
echo "
<div class=\"user-input-company\">
<input type=\"text\" name=\"company\" id=\"company\" required/>
<span class=\"company\">company</span>
</div>";}
else if (substr($getWholeUrl , -2)=='a2') {
echo "
<div class=\"user-input-url\">
<input type=\"text\" name=\"url\" id=\"url\" required/>
<span class=\"url\">Link of media</span>
</div>";}
else if (substr($getWholeUrl , -2)=='e3'){
echo "
<div class=\"user-input-zipcode\">
<input type=\"text\" name=\"zipcode\" id=\"zipcode\" required/>
<span class=\"zipcode\">Zipcode</span>
</div>"
;}?>
<?php if (substr($getWholeUrl , -2)=='e3' || substr($getWholeUrl , -2)=='a2' || substr($getWholeUrl , -2)=='p4'){
echo "
<input type=\"Date\" name=\"birthday\" id=\"birthday\" min=\"1930-01-01\" max=\"2020-12-29\" value=\"2000-01-01\">
<span class=\"birthday\">birthday</span>
";}
else echo "<br><br><br><br><br>"
?>
<?php if (substr($getWholeUrl , -2)=='e3') {
echo "
<div class=\"user-input-attachment\">
<div>"; if(isset($error)) echo $error; echo "</p></div>
<input type=\"file\" name=\"attachment\" id=\"attachment\" value=\"\"/>
<span class=\"attachment\">attachment:</span>
</div>"; }
else if (substr($getWholeUrl , -2)=='p4' || substr($getWholeUrl , -2)=='a2') { echo "<br><br><br><br><br><br>";}
else if (substr($getWholeUrl , -2)=='o1') { echo "<br><br><br><br><br>";}
?>
<div class="user-input-idcard">
<div><p><?php if(isset($error)) echo $error;?></p></div>
<input type="file" name="pi" id="pi" value=""/>
<span class="idcard">identity card :</span>
</div>
<input type="submit" id="send" name="send" value="Send"/>
</div>
</form>
</section>
</div>
</div>
</div>
</body>
</html>
What is the problem with my code I can make it work but the error Notice: Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\PHP\index.php on line 50 is appearing above.
The real problem is if I make if($check_email > 0){ to if($check_email_row > 0){ I can't make the error message "Email is already registered" to show below the email textbox and adding the same existing email.
<?php
include("connection.php");
$name = $address = $email = $password = $cpassword = "";
$nameErr = $addressErr = $emailErr = $passwordErr = $cpasswordErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])){
$nameErr = "Name is required!";
}
else{
$name = $_POST["name"];
}
if(empty($_POST["address"])){
$addressErr = "address is required!";
}
else{
$address = $_POST["address"];
}
if(empty($_POST["email"])){
$emailErr = "email is required!";
}
else{
$email = $_POST["email"];
}
if(empty($_POST["password"])){
$passwordErr = "Password is required!";
}
else{
$password = $_POST["password"];
}
if(empty($_POST["cpassword"])){
$cpasswordErr = "Confirm Password is required!";
}
else{
$cpassword = $_POST["cpassword"];
}
if($name && $address && $email && $password && $cpassword){
$check_email = mysqli_query($connections,"SELECT email FROM mytbl WHERE email='$email'");
$check_email_row = mysqli_num_rows($check_email);
if($check_email > 0){
$emailErr = "Email is already registered!";
}else{
$query = mysqli_query($connections, "INSERT INTO mytbl (name,address,email,password,account_type)
VALUES ('$name','$address','$email','$cpassword','2')");
echo "<script language='javascript'>alert('New Record Has Been Added!')</script>";
echo "<script>window.location.href='index.php';</script>";
}
}
}
?>
<style>
.error{
color:red;
}
</style>
<?php include("nav.php");?>
<br>
<br>
<form method="POST" action="<?php htmlspecialchars("PHP_SELF"); ?>">
Name:<input type="text" name="name" value="<?php echo $name; ?>"> <br>
<span class="error"><?php echo $nameErr; ?></span><br>
Address:<input type="text" name="address" value="<?php echo $address; ?>"> <br>
<span class="error"><?php echo $addressErr; ?></span><br>
Email:<input type="text" name="email" value="<?php echo $email; ?>"> <br>
<span class="error"><?php echo $emailErr; ?></span><br>
Password:<input type="password" name="password" value="<?php echo $password; ?>"> <br>
<span class="error"><?php echo $passwordErr; ?></span><br>
Confirm Password:<input type="password" name="cpassword" value="<?php echo $cpassword; ?>"> <br>
<span class="error"><?php echo $cpasswordErr; ?></span><br>
<input type="submit" value="Submit">
</form>
<hr>
<?php
$view_query = mysqli_query($connections, "SELECT * FROM mytbl");
echo "<table border='1' width='50%'>";
echo "<tr>
<td>Name</td>
<td>Address</td>
<td>Email</td>
<td>Option</td>
</tr>";
while($row = mysqli_fetch_assoc($view_query)){
$user_id = $row["id"];
$db_name = $row["name"];
$db_address = $row["address"];
$db_email = $row["email"];
echo "<tr>
<td>$db_name</td>
<td>$db_address</td>
<td>$db_email</td>
<td>
<a href='Edit.php?id=$user_id'>Update</a>
<a href='ConfirmDelete.php?id=$user_id'>Delete</a>
</td>
</tr>";
}
echo"</table>";
?>
<hr>
<?php
$names = array("ian","Joshua","vinoya");
foreach($names as $display_names) {
echo $display_names . "<br>";
}
?>
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>
I am still a beginner at PHP/MYSQL and I am having difficulties inserting data into my MYSQL database. (I've originally tried using my localhost database but once i moved to an online server, everything seems to stop working.)
Right now, as soon as i submit the data from my index.php page.. it only refreshes the page and doesn't add any data.
However, when I go to submit.php, everything works fine and it adds an empty set of data to my results.php.
My codes are as follows. Any help will be greatly appreciated. Thank you!
Index.php
<html>
<head>
<title>POST variables</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="all">
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if (!$con) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo '<div class="container">
<form id="profiles">
<div class="header">
<h3>Hello there!</h3>
<p>We want to know more about you! Share a few interesting details about yourself using the form below!</p>
</div>
<div class="sep"></div>
<div class="inputs">
<form action="submit.php" method="post">
<input id="name" name="name" placeholder="Full Name" required="" autofocus="" autocomplete="on" type="text">
<input id="email" name="email" placeholder="Email Address" required="" autofocus="" autocomplete="on" type="text">
<input id="colour" name="colour" placeholder="Favourite Colour" required="" autofocus="" autocomplete="on" type="text">
<input id="music" name="music" placeholder="Favourite Song" required="" autofocus="" autocomplete="on" type="text">
<input id="superpower" name="superpower" placeholder="If you had a superhero ability, what would it be?" required="" autofocus="" autocomplete="on" type="text">
<button id="submit" type="submit"name="submit" value="added">Submit!</button>
</form> </div>
</div>';
?>
</body>
</html>
Submit.php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_POST["name"])){
$name = $_POST["name"];
} else {
$name = "";
}
if(isset($_POST["email"])){
$email = $_POST["email"];
} else {
$email = "";
}
if(isset($_POST["colour"])){
$colour = $_POST["colour"];
} else {
$colour = "";
}
if(isset($_POST["music"])){
$music = $_POST["music"];
} else {
$music = "";
}
if(isset($_POST["superpower"])){
$superpower = $_POST["superpower"];
} else {
$superpower = "";
}
$sql = "INSERT INTO profiles (name, email, colour, music, superpower) VALUES ('$name', '$email', '$colour', '$music', '$superpower')";
if(mysqli_query($con, $sql)){
header ('location: results.php'.$query_string);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}
if($name !== "" && $email !== "" && $colour !== "" && $music !== "" && $superpower !== "") {
$query_string = '?name=' . $name.'&email='.$email.'&colour='.$colour.'&music='.$music.'&superpower='.$superpower;
header('HTTP/1.1 303 See Other');
header ('location: results.php'.$query_string);
}
?>
And my results page.
<html>
<head>
<title>POST Success</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_GET["name"])){
$name = $_GET["name"];
} else {
$name = "no name";
}
if(isset($_GET["email"])){
$email = $_GET["email"];
} else {
$email = "no email";
}
if(isset($_GET["colour"])){
$colour = $_GET["colour"];
} else {
$colour = "no colour:";
}
if(isset($_GET["music"])){
$music = $_GET["music"];
} else {
$music = "music";
}
if(isset($_GET["superpower"])){
$superpower = $_GET["superpower"];
} else {
$superpower = "superpower";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM profiles");
echo "<div style='border:solid 1px #ccc;padding:10px;float:left;margin-top:10px;'>";
echo "<table border='1'> <tr> <th>Name</th> <th>Email</th> <th>Favourite Colour</th>
<th>Favourite Music</th>
<th>Superhero Ability</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['colour'] . "</td>";
echo "<td>" . $row['music'] . "</td>";
echo "<td>" . $row['superpower'] . "</td>";
echo "</tr>";}
echo "</table>";
echo "</div>";
mysqli_close($con);
?>
</body>
</html>
Your form has no action, so it'll submit the form to the URL you loaded the page from, which will be index.php.
You need this:
<form id="profiles" action="Submit.php" method="POST">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the method portion as well - with no method, forms default to using GET
Be careful you have two form in your index.php.
<form id="profiles">
and
<form action="submit.php" method="post">
I think the first one is useless.
I have created a register form that includes 3 drop lists, each one of those is related to the selection of the before one so I need to use the ajax but the result that I get is that the first drop list works fine but the 2 others do not work it just displays the default value <choose>
I just need to fix the 3 drop list but I displayed all the code to make others understand what I need.
register.php
<?php require_once('include/connect.php'); ?>
<?php
function specializationQuery(){
$specData = mysql_query("SELECT * FROM specialization");
while($recordJob = mysql_fetch_array($specData)){
echo'<option value="' . $recordJob['specialization_id'] . '">' . $recordJob['specialization_name'] . '</option>';
}
}
//default value
$message = "Fields Marcked with an [*] are Required";
$username = "";
$fname = "";
$lname = "";
$specialization = "";
$email = "";
$pass1 = "";
$pass2 = "";
$governorate="";
$district = "";
$village = "";
if(isset($_POST['username'])){
$username = mysql_real_escape_string($_POST['username']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$pass1 = mysql_real_escape_string($_POST['pass1']);
$pass2 = mysql_real_escape_string($_POST['pass2']);
$bdate = mysql_real_escape_string($_POST['birthdate']);
$specialization = mysql_real_escape_string($_POST['specialization']);
$governorate = mysql_real_escape_string($_POST['governorate']);
$district = mysql_real_escape_string($_POST['district']);
$village = mysql_real_escape_string($_POST['village']);
var_dump($fname);
var_dump($username);
var_dump($governorate);
var_dump($email);
//error handeling
if((!$username)||(!$fname)||(!$lname)||(!$email)||(!$pass1)||(!$pass2)||(!$specialization)||(!$governorate)||(!$district)||(!$village)){
$message = "**** Please insert the Required Fields below ****<br />";
if($fname == "")
{
$message = $message . "Enter First name<br/>";
}
if($lname == "")
{
$message = $message . "Enter Last name<br/>";
}
if( $specialization == 0)
{
$message = $message . "Select Your Job<br />";
}
if($governorate == 0)
{
$message = $message . "Select Your Governorate<br />";
}
if($district == '0')
{
$message = $message . "Select Your District<br />";
}
if($village == '0')
{
$message = $message . "Select Your Village<br />";
}
if($email == "")
{
$message = $message . "Enter Email Adress<br/>";
}
if ($username == "") {
$message = $message . "Enter User Name<br/>";
}
if($pass1 == "")
{
$message = $message . "Enter password<br/>";
}
if($pass2 == "")
{
$message = $message . "rechek the password <br/>";
}
}
elseif(strlen($pass1) <= 8)
{
$message = $message . "Your Password must be at least 8 charachters<br />";
}
else if($pass1!=$pass2){
$message = "your password do not match!";
}
else
{
//securing the data
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
//$pass1 = sha1($pass1);
$email = mysql_real_escape_string($email);
// checking for duplicate
$user_query = mysql_query("SELECT user_name FROM user WHERE user_name = '$username'LIMIT 1") or die("could not check the username");
$count_username = mysql_num_rows($user_query);
$email_query = mysql_query("SELECT email_address FROM user WHERE email_address = '$email'LIMIT 1") or die("could not check the email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0){
$message = " your username is alredy in use";
}elseif($count_email > 0){
$message = "your email is alredy in use";
}
else{
$query = mysql_query("INSERT INTO user(user_name, first_name, last_name, governorate, district, village, birth_date, email_address, specialization, password, registered_date)VALUES('$username', '$fname', '$lname', '$governorate', '$district', '$village', '$bdate', '$email', '$specialization', '$pass1', now())")or die("could not insert data");
$message = "you have now been registered";
if ($query)
{
$_SESSION['user_id'] = mysql_insert_id();
$_SESSION['login'] = 'true';
$_SESSION['login_user'] = $username;
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>RegisterPage</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel|Satisfy' rel='stylesheet' type='text/css' />
<link href="default.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#village").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
});
$("select#district").change(function(){
id = $(this).val();
$("select#village").attr("disabled","disabled");
$("select#village").html("<option>wait...</option>");
$.post("select_village.php", {id:id}, function(data){
$("select#village").removeAttr("disabled");
$("select#village").html(data);
});
});
$("form#registerform").submit(function(){
var cat = $("select#governorate option:selected").attr('value');
var type = $("select#district option:selected").attr('value');
var village = $("select#village option:selected").attr('value');
});
});
</script>
</head>
<body>
<div id="banner">
<div id="header-wrapper">
<div id="header">
<img src="images/web_header copy.jpg" width="1160" height="150" alt="" />
</div>
</div>
</div>
<div id="wrapper">
<div id="page-wrapper">
<div id="page">
<div id="wide-content">
<h2 class="registerTitle">Registration Fields</h2>
<h3 class="registerTitle">Sign Up Today....</h3>
<br /><br />
<br />
<br />
<br />
<p style="color:#FF0000" align="center"><?php print("$message")?></p>
<!--registration fields-->
<?php require_once('include/select.class.php'); ?>
<form id="registerform" action="register.php" method="post">
first name<span class="required-fields">*</span><br />
<input type="text" name="fname" placeholder="Firstname" /><br /><br />
last name<span class="required-fields">*</span><br />
<input type="text" name="lname" placeholder="Lastname" />
<br /> <br />
Date of Birth<br />
<input type="date" name="birthdate" value= "YYYY_MM_DD" onfocus="if (this.value == 'YYYY_MM_DD') {this.value = '';}" onblur="if (this.value == '') {this.value = 'YYYY_MM_DD';}" /><br /><br />
Specialization:<span class="required-fields">*</span><br />
<select name="specialization" class="select">
<option value="0">-- Select Your Specialization --</option>
<?php specializationQuery(); ?>
</select>
<br /> <br />
Governorate<span class="required-fields">*</span><br />
<select id="governorate" name = 'governorate'>
<?php echo $opt->ShowGovernorate(); ?>
</select><br /><br />
District<span class="required-fields">*</span><br />
<select id="district" name="district">
<option value="0">choose...</option>
</select><br /><br />
Village<span class="required-fields">*</span><br />
<select id="village" name="village">
<option value="0">choose...</option>
</select>
<br /> <br />
Email:<span class="required-fields">*</span><br />
<input type="text" name="email" placeholder="Email Adress" /><br /><br />
Username:<span class="required-fields">*</span><br />
<input type="text" name="username" placeholder="Username" />
<br /><br />
Password:<span class="required-fields">*</span><br />
<input type="password" name="pass1" placeholder="Password" /><br /><br />
Re_Password:<span class="required-fields">*</span><br />
<input type="password" name="pass2" placeholder="Validate Password" />
<br /><br />
<input type="submit" value="Register"/>
</form>
<!--end of registration fields-->
</div>
</div>
</div>
</div>
<div id="footer-bg">
<div id="footer-content" class="container">
<div id="column3">
<h2>About Us</h2>
<ul class="style1">
<li class="first">Lam El Chamel is the first web development system for me, this system had allow me to expand my knowledge and had put me in the first step of the programming career.
Hope that this system will respnd for user's requirements, and as each system it will have a future enhancment with taking into consideration users feedback in the feedback section.
</li>
</ul>
</div>
<div id="column4">
<h2>Navigation</h2>
<ul class="style1">
<li class="first">Home</li>
<li>Map</li>
<li>Feedback</li>
<li>Search</li>
<li>Help</li>
</ul>
</div>
</div>
</div>
<div id="footer" class="container">
<p>Copyright (c) 2013 Lam_El_Chamel.zxq.net All rights reserved. Design by Georges Matta.
</div>
</body>
</html>
select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "dbconfig.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowGovernorate()
{
$sql = "SELECT * FROM governorate";
$res = mysql_query($sql,$this->conn);
$governorate = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$governorate .= '<option value="' . $row['governorate_id'] . '">' . $row['governorate_name'] . '</option>';
}
return $governorate;
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
var_dump($res);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
public function ShowVillage()
{
$sql = "SELECT id, village_name FROM village WHERE district_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$village = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$village .='<option value="' .$row['village_id'] . '">' . $row['village_name'] . '</option>';
}
return $village;
}
}
$opt = new SelectList();
?>
select_village.php
<?php
require_once('include/select.class.php');
echo $opt->ShowVillage();
?>
select-district.php
<?php
require_once('include/select.class.php');
echo $opt->ShowDistrict();
?>
in select.class.php better you define two variable, for using your posted variable. like:
<?php
class SelectList {
protected $conn;
public $governorate_id;
public $district_id;
public function __construct()
{
$this->DbConnect();
}
}
?>
in functions ShowDistrict() and ShowVillage() you can use these variables.
use $this->varName instead of $_POST[id].
like:
<?php
class SelectList {
protected $conn;
public $governorate_id;
public $district_id;
public function __construct()
{
$this->DbConnect();
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=".$this->governorate_id;
$res = mysql_query($sql,$this->conn);
var_dump($res);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
public function ShowVillage()
{
$sql = "SELECT id, village_name FROM village WHERE district_id=".$this->district_id;
$res = mysql_query($sql,$this->conn);
$village = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$village .='<option value="' .$row['village_id'] . '">' . $row['village_name'] . '</option>';
}
return $village;
}
}
?>
so now you just get posted variable in select_village.php and select-district.php.
select_village.php:
<?php
require_once('include/select.class.php');
$opt->governorate_id = $_POST['id'];
echo $opt->ShowVillage();
?>
select-district.php:
<?php
require_once('include/select.class.php');
$opt->district_id = $_POST['id'];
echo $opt->ShowDistrict();
?>