PHP sending form accorded to a url token - php

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>

Related

Fatal error: Uncaught PDOException:PDO There is no active transaction in /home/qndt0n0hz1u8/public_html/register.php:185 Stack trace

I am new to server mysql database, i just hosted my server with godaddy, connected to the database, my select query is working fine. After several trouble shooting i decided to use pdo transactions but am getting this error
My php registration script for insertion into database which is not working is show below:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once('dbh.php');
require_once'config.php';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['f_name']) && isset($_POST['u_name']) && ($_POST['f_name']) !="" && ($_POST['u_name']) !="" && ($_POST['Email']) !="" && ($_POST['phonenumber']) !="" ) {
/* id should be an auto-increment field in the db */
$f_name = isset($_POST['f_name']) ? $_POST['f_name'] : false;
$u_name = isset($_POST['u_name']) ? $_POST['u_name'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$password1 = isset($_POST['password1']) ? $_POST['password1'] : false;
$Email = isset($_POST['Email']) ? $_POST['Email'] : false;
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : false;
$sponsor = isset($_GET['sponsor']) ? $_GET['sponsor'] : false;
echo $sponsor;
$error_fname = "";
$eror_fname = "";
$errror_fname = "";
$eror_uname = "";
$errror_uname = "";
$error_uname = "";
$eror_password = "";
$errror_password = "";
$error_password = "";
$eror_email = "";
$error_email = "";
$errror_email = "";
$eror_phonenumber = "";
$error_phonenumber = "";
$errror_phonenumber = "";
$error_captcha = "";
$error_sponsor = "";
$errorSmt = "";
if(isset($_POST['f_name']) && isset($_POST['u_name']) && isset(($_POST['Email'])) && isset($_POST['phonenumber']) ) {
$errror_fname = $f_name.' is OK';
//check for duplicate username
$con= new PDO("mysql:host=$serverhost;dbname=silverhub;" , $serverusername, $serverpassword);
$query = $con->prepare("SELECT userid FROM users WHERE u_name=? LIMIT 1");
$u_Check = $query->bindParam(1, $u_name, PDO::PARAM_STR);
$u_Check = $query->execute();
$u_Check = $query->rowCount();
if( $u_Check=$query->rowCount() > 0) {
$eror_uname = ' Sorry'.$u_name.' already taken, please choose another';
}else{
$errror_uname = $u_name.' is OK';
}
//check for duplicate referral
$query = $con->prepare("SELECT sponsor FROM users WHERE userid=? LIMIT 1");
$s_Check = $query->bindParam(1, $userid, PDO::PARAM_INT);
$s_Check = $query->execute();
$s_Check= $query ->fetch(PDO::FETCH_ASSOC);
if( $s_Check['sponsor'] == $u_name) {
$error_sponsor = 'Sorry, user cannot refer himself';
}
//check referral Email
$query = $con->prepare("SELECT userid FROM users WHERE Email=? LIMIT 1");
$e_Check = $query->bindParam(1, $Email, PDO::PARAM_STR);
$e_Check = $query->execute();
$e_Check = $query->rowCount();
if( $p_Check=$query->rowCount() > 0) {
$eror_email = $Email.' already taken, please choose another';
}else{
$errror_email = $Email. ' is OK';
}
//check for duplicate phonenumber
$query = $con->prepare("SELECT userid FROM users WHERE phonenumber=? LIMIT 1");
$p_Check = $query->bindParam(1, $phonenumber, PDO::PARAM_STR);
$p_Check = $query->execute();
$p_Check = $query->rowCount();
if( $al_Check=$query->rowCount() > 0) {
$eror_phonenumber = $phonenumber.' already taken, please choose another';
}else{
$errror_phonenumber = $phonenumber. ' is OK';
}
}
// if(!preg_match("/^[a-zA-Z0-9]*$/",$f_name) && strip_tags(trim($f_name))) {
// $error_fname = 'invalid, fullname must be alphanumerics with no whitespace';
// echo 'invalid, fullname must be alphanumerics with no whitespace';
// }
if(!preg_match("/^[a-zA-Z0-9]*$/",$u_name) && strip_tags(trim($u_name))) {
$error_uname = 'invalid, username must be alphanumerics with no whitespace';
}
if(strlen($u_name) < 3 || strlen($u_name) > 16) {
$error_uname = 'Username must be between 3 - 16 characters';
}
if($password !== $password1) {
$error_password = 'Password and RepeatPassword do not match';
}
if(strlen($password) < 5) {
$error_password = 'Weak password, Password must be more than 5 characters';
}
if(strlen($phonenumber) > 11 && trim(htmlentities($phonenumber))) {
$error_phonenumber = 'Phonenumbers must be an 11 digit number';
}
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$error_email = ' invalid email address, please verify your email address';
}
if(!preg_match("/^[a-zA-Z0-9]*$/",$sponsor) && strip_tags(trim($sponsor))) {
$error_sponsor = 'invalid sponsor name, must be alphanumeric ';
}
if(empty($_POST['recaptcha'])) {
$error_captcha = 'Enter the Verification Code Above';
}
elseif($_POST['recaptcha'] != $_SESSION['recaptcha']) {
$error_captcha = 'Verification Code did not match, try again';
}elseif($_POST['recaptcha'] == $_SESSION['recaptcha']) {
$error_captcha = 'Verification Matched, Click Register';
}
if($u_name && $eror_fname =="" && $error_fname =="" && $errror_fname !=="" && $eror_uname =="" && $error_uname =="" && $errror_uname !=="" && $error_password =="" && $eror_email == "" && $error_email == "" && $errror_email !== "" && $eror_phonenumber =="" && $error_phonenumber =="" && $errror_phonenumber !=="" ) {
class reg extends dbh {
public function userCheck($f_name, $u_name,$password,$Email,$phonenumber,$sponsor) {
try {
$con = new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$con->beginTransaction();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$passenc = password_hash($password, PASSWORD_DEFAULT, array('cost'=>11));
$emailCode = rand().$phonenumber;
$smsCode = rand().$u_name;
$Active = 0;
$Has_reserved_person = 'NO';
$MainTime = time();
$con= new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$sql = "INSERT INTO users (f_name,u_name,password,Email,emailCode,phonenumber,smsCode,sponsor,Active,Has_reserved_person,MainTime) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
$insert = $con->prepare($sql);
$insert->bindParam(1,$f_name,PDO::PARAM_STR);
$insert->bindParam(2,$u_name,PDO::PARAM_STR);
$insert->bindParam(3,$passenc );
$insert->bindParam(4,$Email,PDO::PARAM_STR);
$insert->bindParam(5,$emailCode,PDO::PARAM_STR);
$insert->bindParam(6,$phonenumber,PDO::PARAM_STR);
$insert->bindParam(7,$smsCode,PDO::PARAM_STR);
$insert->bindParam(8,$sponsor,PDO::PARAM_STR);
$insert->bindParam(9,$Active);
$insert->bindParam(10,$Has_reserved_person);
$insert->bindParam(11,$MainTime);
$insert->execute();
$con->commit();
if($insert->execute()){
echo 'insert successfull';
}else{
echo "Execute query error, because:" . print_r($con->errorinfo());
return false;
}
} catch (PDOException $e){
throw $e;
}
}
}
$object = new reg();
$object->userCheck( $f_name, $u_name, $password, $Email, $phonenumber, $sponsor);
}
}
?>
Here is my HTML FORM input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html !doctype>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="container">
<div id="sec">REGISTER WITH US</div>
<img src="images/images(33).jpg">
<form action='register.php' method='POST' class='ajax-reg'>
<!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
<div class='form-group'>
<p> Note!!! Fields with astericks must be filled</p>
<input type='hidden' class='form-control' name='userid' placeholder='enter your id' />
</div>
<br>
<div class='form-group'>
<label>fullname*</label>
<input type="text" class="form-control" onblur ="fnamecheck()" id="f_name" name="f_name" placeholder="Enter your fullname" value="<?php echo #$_POST['f_name']?>" /><span id ="fullnameStatus"></span>
</div>
<br>
<div class='form-group'>
<label>username*</label>
<input type="username" class="form-control" name="u_name" id ="u_name" onblur ="usernamecheck()" placeholder="Enter your username" value="<?php echo #$_POST['u_name']?>" /><span id ="usernameStatus"></span>
</div>
<br>
<div class='form-group' >
<label>password*</label>
<input type="password" class="form-control" name="password" id="password" onblur ="passcheck()" placeholder="type in your password" />
</div>
<br>
<div class='form-group' >
<label>RepeatPassword*</label>
<input type="password" class="form-control" name="password1" id ="password1" onblur ="passcheck()" placeholder= "Retype in your password" /><span id ="passwordStatus"></span>
</div>
<br>
<div class='form-group'>
<label>email*</label>
<input type="email" class="form-control" name="Email" id ="Email" onblur ="emailcheck()" placeholder="Enter your email" value="<?php echo #$_POST['Email']?>" /><span id ="emailStatus"></span>
</div>
<br>
<div class='form-group'>
<label>phonenumber*</label>
<input type="number" class="form-control" name="phonenumber" id = "phonenumber" onblur ="phcheck()" placeholder="Enter your phonenumber" value="<?php echo #$_POST['phonenumber']?>" /><span id ="phonenumberStatus"></span>
</div>
<br>
<div>
<?php if (isset($_GET['sponsor']) && $_GET['sponsor'] != "") {?>
<input type="hidden" class="form-control" name="sponsor" id ="sponsor" onblur ="usernamecheck()" placeholder="type in your sponsor username here" value="<?php $sponsor = $_GET['sponsor'];?>" />
<?php }?>
</div>
<br>
<div id="captcha"><img src="captcha.php"></div>
<br>
<div id="refresh"><p> Refresh To Change Code</p></div>
<div id="captcha">
<input type="text" class="form-control" name="recaptcha" id = "recaptcha" onblur ="recaptchacheck()" placeholder="Enter The Code Above" /><span><?php echo #$error_captcha?></span><span id ="recaptchaStatus"></span>
</div>
<div class='form-group'>
<!-- this checkbox needs a name!! Assign name `terms` -->
<input type="checkbox" name="terms" required />
</div>
<div id="terms"> </a><a href="terms.php" >I agree with terms and conditions</a></div>
<div>
<input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
</div>
<br>
</form>
<br>
<div></div>
</div>
<footer>
</footer>
<script lang="javascript" type="text/javascript" src="jqueryfunctions.js"></script>
<script lang="javascript" type="text/javascript" src="ajaxfiles.js">
</script>
</body>
</html>

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'];
?>

Update row data with id not carrying id forward

Have being trying this query for 3 days now. I have a list of rows here: http://prntscr.com/dick00. All what I want to is to edit and delete each row respectively. For some reason the id is not carrying forward and no record is updating.
When I click on edit in access.php I get edit_access.php?id= in address bar.
Here is my link in access.php
<td><a href="edit_access.php?id=<?php echo $row['id']; ?>"><i class="fa fa-edit"></i>edit</td>
edit_access.php
EDIT 1: php code
<?php
// start session
session_start();
// error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['user_type'])){
header('Location: index.php');
}
// include connection
require_once('include/connection.php');
// set user session variables
$userId = $_SESSION['user_id'];
$error = [] ;
if(isset($_POST['update']))
{
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$therapist = $_POST['therapist'];
$access_type = $_POST['access_type'];
$code = $_POST['code'];
$created_at = $_POST['created_at'];
$postcode = $_POST['postcode'];
// validate form field
if (empty($firstname)){
$error[] = 'Field empty, please enter patient first name';
}
if (empty($lastname)){
$error[] = 'Field empty, please enter patient last name';
}
if (empty($therapist)){
$error[] = 'Field empty, please enter your name';
// $error = true;
}
if (empty($code)){
$error[] = 'Field empty, please enter patient access code';
// $error = true;
}
if (empty($access_type)){
$error[] = 'Field empty, please check access type';
// $error = true;
}
if (empty($postcode)){
$error[] = 'Field empty, please enter patient postcode';
// $error = true;
}
//if no errors have been created carry on
if(empty($error)){
$updated_at = date('Y-m-d');
// ************* UPDATE PROFILE INFORMATION ************************//
if(!($stmt = $con->prepare("UPDATE access SET firstname = ?, lastname = ?, therapist = ?, access_type = ?, postcode = ?, code = ?, updated_at = ?
WHERE id = ?"))) {
echo "Prepare failed: (" . $con->errno . ")" . $con->error;
}
if(!$stmt->bind_param('sssssssi', $firstname, $lastname, $therapist, $access_type, $postcode, $code, $updated_at, $userId)){
echo "Binding paramaters failed:(" . $stmt->errno . ")" . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
}
if($stmt) {
$_SESSION['main_notice'] = '<div class="alert alert-success">"Access Code Added successfully!"</div>';
header('Location: access.php');
exit;
}else{
$_SESSION['main_notice'] = '<div class="alert alert-danger">"Some error, try again"</div>';
header('Location: '.$_SERVER['PHP_SELF']);
}
}
}
// title page
$title = "Edit Access Record | Allocation | The Whittington Center";
// include header
require_once('include/header.php');
?>
<?php
if(isset($_GET['id'])){
$userId = $_GET['id'];
}
else{
$userId = $_POST['user_id'];
// mysqli_close($con);
$stmt = $con->prepare("SELECT * FROM access WHERE id = ?");
$stmt->bind_param('s', $userId);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0) {
echo 'No Data Found for this user';
}else {
$stmt->bind_result($firstname, $lastname, $therapist, $access_type, $postcode, $code);
while ($row = $stmt->fetch());
$stmt->close();
}
?>
EDIT 2: HTML part
<h2 class="text-light text-greensea">Edit Access Record</h2>
<form name="access" class="form-validation mt-20" novalidate="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete='off'>
<div class="form-group">
<input type="text" name="firstname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' firstname ']; } ?>' placeholder='firstname'></td>
</div>
<div class="form-group">
<input type="text" name="lastname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' lastname ']; } ?>' placeholder='lastname'></td>
</div>
<div class="form-group">
<input type="text" name="therapist" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' therapist ']; } ?>' placeholder='therapist'></td>
</div>
<?php $access_type = $access_type; ?>
<div class="form-group ">
<label for="work status">Access Type</label>
<div name="access_type" value='<?php if(isset($error)){ echo $_POST[' access_type ']; } ?>'>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($work_status) && $access_type == "Keysafe") echo "checked"; ?> value="Keysafe"><i></i>Keysafe
</label>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($access_type) && $access_type == "keylog") echo "checked"; ?> value="keylog"><i></i>Keylog
</label>
</div>
</div>
<div class="form-group">
<input type="text" name="code" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' code ']; } ?>' placeholder='access code'></td>
</div>
<div class="form-group">
<input type="text" name="postcode" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' postcode ']; } ?>' placeholder='postcode'></td>
</div>
<div class="form-group text-left mt-20">
<button type="update" class="btn btn-primary pull-right" name="update" id='update'>Add Access</button>
<!-- <label class="checkbox checkbox-custom-alt checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label> -->
<a href="access.php">
<button type="button" class="btn btn-greensea b-0 br-2 mr-5">Back</button>
</a>
</div>
</form>
</div>
<!-- end of container -->
Thanks guy's for requesting for more code... i hope have given enough code sample.
you most put your id inside of a hidden input in your html form like this:
<input type="hidden" name="itemId" value="<?php echo '$_GET['id']'?>">
and then when you submit your form you have itemId in side $_POST['itemId'] variable.
EDIT:
I must describe scenario for you. maybe you got the point.
you have a list of access witch in every row has this tag:
access ....
in your access-form.php you have a form with this structure:
<form method="post" action="edit-access.php">
.....
<input type="hidden" name="id" value="<?php echo $_GET['id']?>">
.....
</form>
next in your edit-access.php you can access to this id by this syntax:
echo $_POST['id'];

Problems inserting data into MYSQL database using PHP

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.

Categories