hi i found a code on internet and edited a bit but i stuck on showing the correct result i want.. when i type the email address i get the correct result but if i have more than 1 entry i always get the last one is it possible to make it show the result based on the email and the date?
here is my code so far
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
$id = "";
$reservation_name = "";
$persons = "";
$date = "";
$time = "";
$email = "";
$status= "";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=multi_edit","root","");
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$email = $_POST['email'];
// mysql search query
$pdoQuery = "SELECT * FROM member WHERE email = :email";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your id to the query id
$pdoExec = $pdoResult->execute(array(":email"=>$email));
if($pdoExec)
{
// if id exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$id = $row['id'];
$reservation_name = $row['reservation_name'];
$persons = $row['persons'];
$date = $row['date'];
$time = $row['time'];
$status = $row['status'];
}
}
// if the id not exist
// show a message and clear inputs
else{
echo 'No Reservation Found On This Email';
}
}else{
echo 'ERROR Something Is Wrong Try Again';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="search.php" method="post">
<center>
Please Enter Your Email Address : <br><br><br><input type="text" name="email" value="<?php echo $email;?>"><br><br>
Reservation Name : <br><input type="text" readonly name="reservation_name" value="<?php echo $reservation_name;?>"><br><br>
Persons : <br><input type="text" readonly name="persons" value="<?php echo $persons;?>"><br><br>
Date Y-M-D : <br><input type="text" name="date" value="<?php echo $date;?>"><br><br>
Time : <br><input type="text" readonly name="time" value="<?php echo $time;?>"><br><br>
Status : <br><input type="text" readonly name="status" value="<?php echo $status;?>"><br><br>
<input type="submit" name="Find" value="Find Data">
</center>
</form>
</body>
</html>
I have work out what you need, it require email (like foobar#gmail.com) and date (like 2018-09-23) in the form input field, if you submit it return the Reservation Name.
Notice for simplicity reason I removed these 3 columns "persons", "time" and "status", but you can add it back, it doesn't change the logic because the finding/query don't need those fields for input
This is my code:
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
function sqlInitConn ($args) {
// Initialze connection.
$serverName = $args["serverName"];
$userName = $args["userName"];
$password = $args["password"];
$dbName = $args["dbName"];
$conn = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
// Those variables are for input to mysql.
$idIpt = "";
$reservation_nameIpt = "";
$emailIpt = "";
$dateIpt = "";
// Those variables are for output to front-end.
$idOpt = "";
$reservation_nameOpt = "";
$emailOpt = "";
$dateOpt = "";
if(isset($_POST['find']))
{
try {
// Connect to mysql.
$pdoConnect = sqlInitConn([
"serverName" => "localhost",
// Change it to your server name.
"userName" => "root",
"password" => "change_it_to__your_password_here_if_your_mysql_need_password",
"dbName" => "multi_edit",
]);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
$emailIpt = $_POST['email'];
$dateIpt = $_POST['date'];
$pdoQuery = "SELECT * FROM member WHERE email = :email AND date = :date";
// Mysql search query
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->bindValue(":email", $emailIpt);
$pdoResult->bindValue(":date", $dateIpt);
$pdoExec = $pdoResult->execute();
if($pdoExec) {
// If record exist, show data in inputs
if($pdoResult->rowCount() > 0) {
foreach($pdoResult as $row) {
$idOpt = $row['id'];
$reservation_nameOpt = $row['reservation_name'];
$emailOpt = $row['email'];
$dateOpt = $row['date'];
break;
// only get first occurrences (get first matching record) to prevent corrupted data
// , because same email might wrongly log twice in same day (= same date), like morning and afternoon.).
}
}
else {
echo 'No Reservation Found On This Email';
// If the id not exist, show a message and clear inputs
}
} else {
echo 'ERROR Something Is Wrong Try Again';
// If the id not exist, show a message and clear inputs
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="" method="post">
<center>
<div>
<p>Please Enter Your Email Address :</p>
<input type="text" name="email" value="<?php echo $emailOpt;?>">
</div>
<div>
<p>Reservation Name :</p>
<input type="text" readonly name="reservation_name" value="<?php echo $reservation_nameOpt;?>">
</div>
<div>
<p>Date Y-M-D :</p>
<input type="text" name="date" value="<?php echo $dateOpt;?>">
</div>
<div>
<input type="submit" name="find" value="Find Data">
</div>
</center>
</form>
</body>
</html>
Related
I want to have a form with php. but for many hours I'm involved an error and the error is when $_POST=['name'] wants to be checked empty or not it is empty.
When I check the database the row is white and nothing is there.
for checking if the $_POST is empty or not I print word 'empty' to be determined it's empty and it will be printed 'empty';
where is my mistake is it related to database mysql or not just in code?
please help me I got confused and bored.
this is whole of my codes:
<!doctype html>
<html lang="fa">
<head>
<meta charset="utf-8">
<title>form</title>
<link href="addContact.css" rel="stylesheet"/>
<link href="main.css" rel="stylesheet"/>
<link href="table.css" rel="stylesheet"/>
</head>
<body>
<?php
$name = "";
$nameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo 'empty';
$nameErr = "Name is required";
} else {
echo 'full';
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO abc (firstname)
VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
thank you in advance
The problem is in use of empty()
You can use it on variables not on values.
See here for PHP documentation page.
To check this, first save it in another variable and then check:
$tempVal = $_POST["name"];
if (empty($tempVal))
you can use this simple example
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
i suggest this:
Understanding $_SERVER['PHP_SELF']
I wanna update just one data from a record using php form but the thing is, when i do that, the rest of the data gets removed from the record.. What do i do :/ here are my codes for updating. What is the mistake i am making.. I am very confused. Would really appreciate some help.
<?php
include('db.php');
if(isset($_POST['update']))
{
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "winc sports";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$country=$_POST['country'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$select = "SELECT * FROM studens WHERE id = '$id'";
$selected = mysqli_query($connect, $select);
$row = mysqli_fetch_assoc($selected);
if (empty($_POST['fname'])) {$fname = $row['fname'];} else {$fname = $_POST['fname'];}
if (empty($_POST['country']))
{
$country = $row['country'];
}
else {
$country = $_POST['country'];
}
if (empty($_POST['id'])) {
$id = $row['id'];
}
else {
$id = $_POST['id'];
}
if (empty($_POST['age'])) {$age = $row['age'];} else {$age = $_POST['age'];}
if (empty($_POST['phone'])) {$phone = $row['phone'];} else {$phone = $_POST['phone'];}
if (empty($_POST['email'])) {$email = $row['email'];} else {$email = $_POST['email'];}
$query = "UPDATE students SET Fname= '$fname', Lname = '$lname', Nationality = '$country', PhoneNumber = '$phone', Email= '$email', Age = '$age' WHERE Id = '$id'";
$result = mysqli_query($connect, $query);
var_dump($result);
if($result)
{
echo 'Data Updated';
}else
{
echo 'Data Not Updated';
}
mysqli_close($connect);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP INSERT DATA USING PDO</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="updating.php" method="post">
<input type="text" name="id" placeholder="Enter new ID"><br><br>
<input type="text" name="fname" placeholder="Enter new First Name"><br><br>
<input type="text" name="lname" placeholder="Enter new Last Name"><br><br>
<input type="number" name="age" placeholder="Enter new age" min="13" max="90"><br><br>
<input type="text" name="country" placeholder="Enter new Nationality"><br><br>
<input type="number" name="phone" placeholder="Enter new Phone Number"><br><br>
<input type="text" name="email" placeholder="Enter new Email"><br><br>
<input type="submit" name="update" value="update">
</form>
</body>
</html>
The select statement is fetching data from a table called studens. This looks like a typo of the actual table so it won't actually fetch any results for you to update. Thus, the data you wind up updating the table with is empty. Rename the initial select table to students and it should properly fetch the data.
Also, please look into prepared statements or various other methods to sanitize inputs. Using POST variables directly in a query makes you extremely vulnerable to SQL Injection.
Hi all I am new to mysqli and php (currently studying and trying to work on a test database- I have not used security measures at this wont be available public) and trying to get the information I have just submitted in the form to display in a new form which will then receive further user input then submitted to database. Here is an example of what I have done so far:
Form 1 (customer table - cust id =primary key)
Customer Details ie name address telephone etc
dynamic drop down box - consists of 4 options.( would like whatever option is selected here to return a particular form)
The form is currently submitting correctly in the database, but I would like once it has submitted to the database to return the customer info (including the customer id as that is the relationship in the new table) and on the form2(service table - service id is primary key) so the user can input further data to the form and submit.
Hope this makes sense, any help would be appreciated.
Thanks
Response 1
Thank you for my response I probably havent made myself very clear.
Form 1 where dynamic dropdown list is - when user submits forms I would like it to return form 2 with the customer info we inserted in form 1
Form 1
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<form action="newbookingcode.php" method="post">
<p>First Name: <input type="text" name="firstname"/>
Last Name: <input type="text" name="lastname"/></p>
<p>Business Name: <input type="text" name="businessname"/></p>
<p>Contact Number: <input type="text" name="number"/>
Alt Number: <input type="text" name="altno"></p>
<p>Email Address:<input type="text" name="email"></p>
<p>Street No:<input tyep="text" name="streetno">
Street Name:<input type="text" name="street"></p>
<p>Suburb:<input type="text" name="suburb">
Postal Code:<input type="text" name="postalcode">
State: <input type="text" name="state"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option**
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value= "'.$row['jobType'].'" >' . $row['jobType'] . '</option>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</p>
</select>
<p>
<input type="submit"/>
</p>
</form>
</body>
</html>
Query in separate file
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType)
VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Check this code and let me know if you have any questions:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
/************** IMPORTANT *************/
$whichForm = 1;//to know which form to show
$last_customer_id = 0;//to store last customer id
//to store your customer information
$fname=$lname=$bname=$phone=$altphone=$email=$streetno=$street=$suburb=$postcode=$state=$service='';
//To handle post operations after clicking on post.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$whichForm = 2; // to show second form
//if it is first form
if($_POST['action'] == 'firstForm')
{
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
//Preparing your insert query
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType) VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
$conn->query($sql); //insert into db
//get last insert customer id and you already have your customer information
//in the variables above $fname, $lname.....etc
$last_customer_id = $conn->insert_id;
}
else{//do something with your second form
//get last customer info
$sql = "SELECT * FROM serviceType where id = ".$POST_['last_customer_id']."";
$result = $conn->query($sql);
$res = $result->fetch_assoc();
//you can access customer information like res['contactFirstName']
}
}
$conn->close(); //close your connection
?>
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<?php
if($whichForm == 1){ //if it is first form
?>
<form id="1" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="firstForm" />
<p>First Name: <input type="text" name="firstname" value="<?php echo $fname; ?>"/>
Last Name: <input type="text" name="lastname" value="<?php echo $lname; ?>" /></p>
<p>Business Name: <input type="text" name="businessname" value="<?php echo $bname; ?>"/></p>
<p>Contact Number: <input type="text" name="number" value="<?php echo $phone; ?>"/>
Alt Number: <input type="text" name="altno" value="<?php echo $altphone; ?>"></p>
<p>Email Address:<input type="text" name="email" value="<?php echo $email; ?>"></p>
<p>Street No:<input tyep="text" name="streetno" value="<?php echo $streetno; ?>">
Street Name:<input type="text" name="street" value="<?php echo $street; ?>"></p>
<p>Suburb:<input type="text" name="suburb" value="<?php echo $suburb; ?>">
Postal Code:<input type="text" name="postalcode" value="<?php echo $postcode; ?>">
State: <input type="text" name="state" value="<?php echo $state; ?>"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//this if to save the value of the selected category
if($row['jobType'] == $service)
{
echo '<option value= "'.$row['jobType'].'" SELECTED>' . $row['jobType'] . '</option>';
}
else
{
echo '<option value= "'.$row['jobType'].'">' . $row['jobType'] . '</option>';
}
}
}
?>
</select></p>
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for if($whichForm == 1)
else if($whichForm == 2){ // or just else will do fine
?>
<form id="2" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="secondForm" />
<!-- This input is needed to store the last customer id -->
<input type="hidden" name="last_customer_id" value="<?php echo $last_customer_id; ?>" />
<!-- here you put your second form -->
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for else if($whichForm == 2)
?>
</body>
</html>
Assuming you are using a database object like mysqli to do DB interactions.
Say form1 generate insert query $insertQyery.
And you are executing this query (insert statement) like
$mysqli->query($insertQyery);
After the execution of this insert statement you can use
$customerId = $mysqli->insert_id
Now using this $customerId you can show records details on form2 or use this $customerId as reference on form2.
After customer submit FORM #1
on the next page
let's get the last customer details :-
<?php
//after mysqli connection
$contactFirstName = '';
$contactLastName = '';
$businessName = '';
$sql_get_data = "SELECT * FROM customer ORDER BY customerID DESC limit 1 ";
$query_get_data = mysqli_query($conn, $sql_get_data);
while ($row = mysqli_fetch_array($query_get_data, MYSQLI_ASSOC)) {
//specify which data you want to get from "customer" table
$contactFirstName = $row['contactFirstName'];
$contactLastName = $row['contactLastName'];
$businessName = $row['businessName'];
}
?>
HTML Form#2 :-
<form id="form2" method="post">
<input type="text" value="<?php echo 'contactFirstName'; ?>"
<input type="text" value="<?php echo 'contactLastName'; ?>"
<input type="text" value="<?php echo 'businessName'; ?>"
</form>
Hope this answer will help you.
I am creating a form to connect to a database using PHP. I have the form semi-functional but when I'm trying to test it by pressing the submit button, it says file not found on the webpage.
Here is code for default.php:
<!DOCTYPE HTML> <html> <head>
<title>PHP FORM - 08246 ACW PART 2</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <style> .error {color:
#FF0000;} </style> </head> <body>
<ul class="w3-navbar w3-black w3"> <li>Home</li> <li>Change location to staff member</li> <li>Current location of all staff</li> <li>Edit personal details of staff member</li> <li>List all locations and show list of people in selected location</li> <li>Staff member and list locations for last24 hours</li> </ul>
<div class="w3-container"> <h2> Web Form </h2> </div>
<div class="w3-container"> <?php // defining the variables and setting them to empty values $first_nameErr = $SurnameErr = $usernameErr = $passwordErr = $previous_LocationErr = $current_LocationErr = $dateErr = $timeErr = $dErr = $tErr = ""; $first_name = $Surname = $username = $password = $previous_Location = $current_Location = $date = $time = $dErr = $tErr = "";
//----validation----
//first name if($_SERVER["REQUEST_METHOD"] == "POST"){ if(empty($_POST["first_name"])){ $first_nameErr = "First Name is required"; }else{ $first_name = test_input($_POST["first_name"]); //validation checking if(!preg_match("/^[a-zA-Z ]*$/",$first_name)){ $first_nameErr = "Please enter only letter and white space"; } }
//surname if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["Surname"])){ $SurnameErr="Surname is required"; }else{ $Surname=test_input($_POST["Surname"]); //validation checking if(preg_match("/^[a-zA-Z ]*$/",$Surname)){ $SurnameErr = " Please enter only letters and white spaces"; } }
//date and time date_default_timezone_set('UTC');
$d = str_replace('/',',', '03/05/2016'); $t = str_replace(':',',', '13:38'); $date = $t.',0,'.$d; $fulldate = explode(',',$date); echo '<br>'; $h = $fulldate[0]; $i = $fulldate[1]; $s = $fulldate[2]; $m = $fulldate[3]; $d = $fulldate[4]; $y = $fulldate[5];
echo date("h-i-s-M-d-Y",mktime($h,$i,$s,$m,$d,$y))."<br>"; echo strtotime ("03/05/2016 13:38");
function test_input($data){ $data=trim($data); $data=stripslashes($data); $data=hmtlspecialchars($data); return $data; } ?>
<?php//database
#server info
#$servername = "SQL2008.net.dcs.hull.ac.uk";
#$username = "ADIR\463142";//userid
#$dbname = "rde_463132"; $servername = "SQL2008.net.dcs.hull.ac.uk"; $username = "username"; $myDB = "examples"; $myLocation = "location";
// Create connection $conn = new mysqli($servername, $username, $myLocation); // Check connection if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
// Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) {
echo "Database created successfully"; } else {
echo "Error creating database: " . $conn->error; }
$conn->close(); ?>
<p><span class="error">* are required field.</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> First Name: <input type="text" name="first_name"><br> <span class="error">* <?php echo $First_nameErr;?></span> <br> Surname: <input type="text" name="Surname"><br> <span class="error">* <?php echo $SurnameErr;?></span> <br> Username: <input type="text" name="username"><br> <span class="error">* <?php echo $username;?></span> <br> Current Location: <input type="text" name="current_Location"><br> <span class="error">* <?php echo $current_Location;?></span> <br> Date: <input type="text" name="date"><br> <span class="error">* <?php echo $date;?></span> <br> Time: <input type="text" name="time"><br> <span class="error">* <?php echo $time;?></span> <br>
<input type="submit" name="submit" value="Submit"> </form>
</div> </body> </html>
I am new to this language and still learning.
Any help or advice would be greatly appreciated.
Thank you
What version of PHP you are using to run this script?
As I can see you are using "Register globals" setting to get $_POST data: http://php.net/manual/en/security.globals.php
If you have PHP version 5.4+ you should use $_POST['form_field_name1'] ... $_POST['form_field_nameN'] to get form data.
Add check:
if (!empty($_POST)) { /* Form validation data goes here */ }
File is incorrect, the form action url points to default.php but your filename is defaul.php
Make if default.php instead of defaul.php
For better handling:
In console of your browser, please check the http call, you can see the error it is showing if its a 500 (check logs / enable the debug mode)
My class is attempting to make our own game.. But, we can't get the submit page to send to the database in PhpMyAdmin. When you click submit, it sends blank entries to the database, like if you hadn't filled in any of the blanks. Can someone help with this problem. Thanks!!
My index.php page.
<html>
<head>
<meta charset="UTF-8">
<title> Register New Account </title>
<link rel="stylesheet" type="text/css" href="td.css">
</head>
<body>
<?php
/* $count=$count+1;
echo " count " . $count; */
if($_POST['submit_id'] == 1)
{
/* echo "testing"; */
if($_POST['Username'] == NULL)
{
$message = 'Please enter your Username.';
}
if($_POST['Email'] == NULL)
{
$message = 'Please enter your Email.';
}
if($_POST['Confirm'] == NULL)
{
$message = 'Please re-enter your Email.';
}
if($_POST['Password'] == NULL)
{
$message = 'Please enter your Password.';
}
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "******", "Tower_Defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
$TableList = " `Username`, `Password`, `Email`, `Confirm` ";
$Values = " '$Username', '$Password', '$Email', '$Confirm' ";
if($message != NULL)
{
echo "$message";
}
?>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <br />
Username: <input type="text" name="Username" id= "Username"> <br />
Email: <input type = "text" name = "Email" id= "Email"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm"> <br />
Password: <input type = "password" name = "Password" id = "Password"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Check if Available!" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
My insert.php page
<html>
<body>
<?php
$Username = $_POST['name'];
$con=mysqli_connect("localhost", "root", "******", "Tower_Defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
UPDATE:
I added in the changes that someone had suggested in moving the checks to insert.php and now the email and confirm email check does not work. Can anyone help?
index.php
<html>
<body>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "insert.php" method = "post"> <br />
Username: <input type="text" name="Username" id= "Username" required = "1"> <br />
Email: <input type = "text" name = "Email" id= "Email" required = "1"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm" required = "1"> <br />
Password: <input type = "password" name = "Password" id = "Password" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
insert.php
<html>
<body>
<?php
if($_POST['submit_id'] == 1)
{
echo "testing";
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "abc123", "tower_defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
}
}
if($message != NULL)
{
echo "$message";
}
$con=mysqli_connect("localhost", "root", "abc123", "tower_defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
</html>
I see two main problems here -
First, the action of your form points to itself. That means that the $_POST array submits to index.php, and your insert.php page has no access to that information. Index.php runs through the validation checks, and if everything checks out, it assigns the $_POST values to variables and quits. That's where the data dies. There is no method for getting the information over to the file insert.php. So if you manually open the file insert.php in a browser, the $_POST array will be empty, and it will simply insert blanks.
There are several ways to resolve this. The simplest, most expeditious way would be the single page solution - move the insert.php code into the index.php file inside that last else block.
else {
//echo "next date <br>";
// create account
$Username = $_POST['name'];
//etc.. code to insert data from insert.php
Another solution would be to move all the validation code to insert.php, display any form errors on that page, and make the user go back a page if validation fails. In that case, you would change the action of the form to insert.php:
<form action="insert.php" method="post">
This approach is less user-friendly, and not an ideal solution. Really a better practice is to use Javascript for form validation and PHP for form processing. That may be outside the scope of your class...
Second, this code is wide open to SQL injection. Instead of putting variables directly into your SQL statements, you need to use parameterized queries. Take a look at this SO question about how to parameterize queries with mysqli.
The mistakes that I found:
First things first your code submits the values received from the form to index.php itself so there is no question of values getting insert at the first place because the insert query is not run.
In index.php check the query to SELECT email and username. The variables do not have any value when the query is run because the values get transferred couple of lines AFTER the queries (at the lines where you have $email = $_POST['Email']). Moreover you have missed the $ sign in the query related to email.
Coming to insert.php you have missed quotes in the global variable $_POST[] in the insert query viz. $_POST['email'].
Check for these errors and let me know if it works.