I am totally new to all things php but I have managed to piece meal together the below form. But for some reason that I don't understand, everytime I hit the submit button it goes to a new page with a value of 0 on it. Here is the page
http://upcycledonline.com/test/Site/myform2.php
<?php
if($_POST['formSubmit'] == "Submit"){
$errorMessage = "";
if(empty($_POST['formEmail'])){
$errorMessage .= "<li>You forgot to enter your email</li>";
}
$varEmail = ($_POST['formEmail'].mysql_real_escape_string);
//$varEmail = $_POST['formEmail'];
if(empty($errorMessage)){
$db = mysql_connect("server","id","password");
if(!$db)
die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
mysql_query($sql);
//$sql = ("INSERT INTO emails(email) VALUES ('%s')".mysql_real_escape_string($varEmail));
//$results = mysql_query($sql);
//$sql = "INSERT INTO emails (emails)"
//. "VALUES ('{$varEmail}');
//mysql_query($sql);
// echo "Details added";
// $_SESSION['status'] = 'success';
}
//header("Location: thankyou.html");
exit();
}
function PrepSQL($value){
// Stripslashes
if(get_magic_quotes_gpc()){
$value = stripslashes($value);
}
// Quote
//this is how I should be doing the escape thing
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
and here is the form
<?php
if(!empty($errorMessage)){
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form id="emailForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post" onSubmit="alert('Thank you. Your email has been added.')">
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" value="<?=$varEmail;?>" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
If they are in one file, it still has a few issues.
Instead of:
$varEmail = ($_POST['formEmail'].mysql_real_escape_string);
Try:
$varEmail = mysql_real_escape_string($_POST['formEmail']);
This should bring the code to the mysql part, and then it will just exit.
The header command can be used to redirect to a "thank you" page, or just echo if success or fail.
Then look for data in your database. :)
BTW:
You almost had it in the PrepSql function, but it is not used.
So you could do: $varEmail = PrepSql($_POST['formEmail']);
Mind the extra '' though.
And cheers for learning to escape data early on! :)
Edit:
You might get an error on the input line in the form where it says <?$varEmail;?>...
There you are using "short tag", meaning you skip the "php" in:
<?php echo $myVar;?>. Also missing "echo".
You can just remove that part - since you get the value from user input.
This echoes my input on my machine (commented out sql for the test):
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter your email</li>";
}
$varEmail = PrepSql($_POST['formEmail']);
//$varEmail = $_POST['formEmail'];
if(empty($errorMessage))
{
/*$db= mysql_connect("server","id","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);*/
echo $varEmail;
//$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
//mysql_query($sql);
//$sql = ("INSERT INTO emails(email) VALUES ('%s')".mysql_real_escape_string($varEmail));
//$results = mysql_query($sql);
//$sql = "INSERT INTO emails (emails)"
//. "VALUES ('{$varEmail}');
//mysql_query($sql);
// echo "Details added";
// $_SESSION['status'] = 'success';
}
//header("Location: thankyou.html");
exit();
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
//this is how I should be doing the escape thing
//$value = "'" . mysql_real_escape_string($value) . "'";
$value = mysql_real_escape_string($value);
return($value);
}
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form id="emailForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onSubmit="alert('Thank you. Your email has been added.')">
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
Related
I have a form that I can post. I also have a sql database that it has a successful connection with. However, when I close the page out, the user input disappears. How can I make the user input part of the page content,almost like a guestbook kind of idea?
<p onclick="myFunction()">Click here to share your personal testimony</p>
<div id="formwindow">
<form action="http://needjesuskneadjesus.org/perstest.php" method="post">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?></span>
<br>
Email: <input type="text" name="email">
<span class="error">* <?php echo $emailErr; ?></span>
<br>
Personal Testimony:<br> <textarea name="personalTestimony" rows="10" cols="50"></textarea><br>
<input type="Submit">
</form>
</div>
<script>
function myFunction() {
document.getElementById("formwindow").style.display = "block";
}
</script>
</br>
<?php
echo "Name: " . $_POST['name'];
?>
</br>
<?php
echo "Email: " . $_POST['email'];
?>
</br>
<?php
echo "Personal Testimony: " . $_POST['personalTestimony'];
?>
</br>
/* Attempt MySQL server connection.
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$personalTestimony = mysqli_real_escape_string($link,
$_REQUEST['personalTestimony']);
// attempt insert query execution
$sql = "INSERT INTO personalTestimony (name, email, testimony) VALUES
('$name', '$email', '$personalTestimony')";
if(mysqli_query($link, $sql)){
echo "Thanks for sharing your personal testimony.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
*/
?>
You can use PHP Sessions to store the users review, this will display the old one
<?php
session_start();
$name;
$email;
$personalTestimony;
if($link === false){
die('ERROR: Could not connect.' . mysqli_connect_error());
}
if (!isset($_POST['name']) && !isset($_POST['email']) && !isset($_POST['personalTestimony'])) {
$name = $_POST['name']);
$email = $_POST['email'];
$personalTestimony = $_POST['personalTestimony']);
// attempt insert query execution
$sql = mysqli_prepare($link, "INSERT INTO personalTestimony (name, email, testimony) VALUES ('$name', '$email', '$personalTestimony'))";
if(mysqli_query($link, $sql)){
echo 'Thanks for sharing your personal testimony.';
} else{
echo 'ERROR: Could not able to execute $sql. ' . mysqli_error($link);
}
} elseif (!empty($_SESSION['name']) || !empty($_SESSION['email']) || !empty($_SESSION['testimony'])) {
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['testimony'] = $personalTestimony;
}
}
// close connection
mysqli_close($link);
?>
I replaced
mysqli_real_escape_string to mysqli_prepare since it's less characters and provides more safety. You can read more about it here.
This will only work until ether the session expires (You can configure this here) or the client clears their cookies.
I'm making a project. There are 4 files: loginMHS, manageLoginMHS (optional), inputPerwalian, db.
In db, the program will connect to database. This is the code:
<?php
$link = mysqli_connect("localhost", "root", NULL, "perwalian");
if (mysqli_connect_errno()) {
die("Connect Error : " . mysqli_connect_error());
}
?>
In loginMHS, user should input their NRP (varchar) & password. This is the code:
<?php
session_start();
?>
<form action="manageLoginMHS.php?act=login" method="POST">
NRP: <input type="text" name="unrp"/><br />
Password: <input type="password" name="upass"/><br />
<input type="submit" value="LOGIN"/>
</form>
I use manageLoginMHS just as a helper file. NRP & varchar from loginMHS will be checked. If user doesn't input NRP, the program show message "Input perwalian belum dapat diakses saat ini". Do I really need this file? Or, I can use only 2 files (loginMHS & inputPerwalian)?
<?php
require './db.php';
session_start();
$act = $_GET['act'];
switch ($act) {
case "login":
$nrp = $_POST['unrp'];
$pass = $_POST['upass'];
$sql = "select * from mahasiswa where nrp = '" . $nrp . "'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
if(isset($_POST['unrp'])){
if(empty($nrp)){
echo "<br /> Input perwalian belum dapat diakses saat ini"
. "<br />";
}
else {
header('Location: inputPerwalian.php');
}
}
if(mysqli_num_rows($result) > 0) {
if($pass == $row['password'] && $nrp == $row['nrp']) {
$_SESSION['login'] = TRUE;
header("Location: inputPerwalian.php");
}
else {
echo "Invalid Password";
}
}
else {
echo "User not found";
}
break;
default:
die("Unknown");
}
?>
Then the program will show data in inputPerwalian from database, which have the same NRP & varchar. This is the code:
<?php
session_start();
if (isset($_SESSION['login'])) {
require './db.php';
//echo $_POST['unrp'];
//$nrp = $_POST['unrp'];
//$pass = $_POST['upass'];
$sql2 = "select nrp, nama, jatah_sks, foto_profil from mahasiswa"
. " where nrp=".$nrp; //this line is the error
$result2 = mysqli_query($link, $sql2);
if (!$result2) {
die("SQL Error " . $sql2);
}
while ($row2 = mysqli_fetch_array($result2)) {
echo "NRP: " . $row2['nrp'] . "<br />";
echo "Nama: " . $row2['nama'] . "<br />";
echo "SKS Maks: " . $row2['jatah_sks'] . "<br />";
echo "Sisa SKS: " . "<br /><br />";
}
}
?>
I have these errors:
Notice: Undefined variable: nrp in C:\xampp\htdocs\ProjectUAS\inputPerwalian.php on line 37
SQL Error select nrp, nama, jatah_sks, foto_profil from mahasiswa where nrp=
So, the program won't show data from database which I have selected before.
What should I do to fix those errors? Please explain your answer. Thank you.
It would be easier to do this with 2 files (or 3 if you want your database connection in a separate file)
You could merge your LoginMHS and ManageLoginMHS pages like this:
<?php
session_start();
require './db.php';
if (isset($_POST['act']))
{
$act = $_POST['act'];
switch($act)
{
case "login":
$nrp = $_POST['unrp'];
$pass = $_POST['upass'];
$sql = "select * from mahasiswa where nrp = '" . $nrp . "'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
if(isset($_POST['unrp'])){
if(empty($nrp)){
echo "<br /> Input perwalian belum dapat diakses saat ini"
. "<br />";
}
else {
header('Location: inputPerwalian.php');
}
}
if(mysqli_num_rows($result) > 0) {
if($pass == $row['password'] && $nrp == $row['nrp']) {
$_SESSION['login'] = TRUE;
$_SESSION['nrp'] = $nrp;
header("Location: inputPerwalian.php");
}
else {
echo "Invalid Password";
}
}
else {
echo "User not found";
}
break;
default:
die("Unknown");
}
}
}
?>
<form action="" method="POST">
<input type="hidden" name="act" value="login" />
NRP: <input type="text" name="unrp"/><br />
Password: <input type="password" name="upass"/><br />
<input type="submit" value="LOGIN"/>
</form>
This combines all login to one form. It sets nrp in a session variable you can read from any other page, so your inputPerwalian page can check it like this: $nrp = $_SESSION['nrp'];
After searching through related questions, I still couldn't get this issue resolved. A "registration successful" page is supposed to pop up after a form is submitted but instead, "No database selected" message appears. where did I miss it. here are the codes.
connect.php
<?php
//connect.php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'esiro';
$connection = mysqli_connect($server, $username, $password, $database);
mysqli_set_charset($connection,"utf8");
?>
signup.php
<?php
//signup.php
include 'connect.php';
include 'header.php';
echo '<h3>Sign up</h3>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo
'<form role="form" method="post" action="" class="cover_form">
<div class="form-group">
<label class="labelfield" for="username">User Name:</label><br>
<input class="inputfield" type="text" name="user_name" class="form-control"/><br>
<label class="labelfield" for="pwd">Password:</label><br>
<input class="inputfield" type="password" class="form-control" id="pwd" name="user_pass"><br>
<label class="labelfield" for="pwd"> Confirm Password:</label><br>
<input class="inputfield" type="password" name="user_pass_check" class="form-control" id="pwd"><br>
<label class="labelfield" for="email">Email Address:</label><br>
<input class="inputfield"type="email" class="form-control" id="email" name="user_email">
</div><br>
<input type="submit" class="btn btn-default" value="Complete Registration"/><br>
</form>
';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(isset($_POST['user_name']))
{
//the user name exists
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'The username can only contain letters and digits.';
}
if(strlen($_POST['user_name']) > 30)
{
$errors[] = 'The username cannot be longer than 30 characters.';
}
}
else
{
$errors[] = 'The username field must not be empty.';
}
if(isset($_POST['user_pass']))
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
else
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly...';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysql_real_escape_string($_POST['user_email']) . "',
NOW(),
0)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
echo 'Successfully registered. You can now sign in and start posting! :-)';
}
}
}
include 'footer.php';
?>
You should Change the script
$result = mysql_query($sql);
Instead of use this
---------------------
$result = mysqli_query($connection,$sql);
And also remove echo mysql_error();
and use this echo mysql_error($connection);
Add this also in instead of mysql_real_escape_string
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysqli_real_escape_string($connection,$_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysqli_real_escape_string($connection,$_POST['user_email']) . "',
NOW(),
0)";
I am making a simple user update page where the user can update the password and their email, but I want to do it with two separate forms, because if I use one, and sent one of the field empty, it will update it to empty in the database. (And I want the user to be able to update only email or only username).
Here is my code:
<html>
<body>
<?php
$con=mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
//
?>
<?php
if(!isset($_POST['submit'])) {
$con=mysqli_connect();
} else {
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
?>
<?php
$email = mysqli_real_escape_string($con,$_POST['Email']);
$password = mysqli_real_escape_string ($con,$_POST['Password']);
$ID = $_SESSION['ID'];
$emailErr = $passwordErr="";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Please enter a valid Email Address";
}
else {
$sql="UPDATE `customer`
SET `Email`='$email'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
echo "Update complete!";
//header("Location: userpage.html");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?> method="post"><br />
Email:<br /> <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br /><br />
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (!preg_match("/^[a-zA-Z0-9#_]*$/",$password))
{
$passwordErr = "Please enter a valid password";
}
else {
$sql="UPDATE `customer`
SET `Password`='$password'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
echo "Update complete!";
//header("Location: userpage.html");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
mysqli_close($con);
?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?> method="post"><br />
Password:<br /> <input type="password" name="Password">
<span class="error">* <?php echo $passwordErr;?></span><br /><br />
<input type="submit">
</form>
</body>
</html>
With this code if I update the second form (which is the password) I will get an error for the first one, because it executes on submit.
How can I make it so that I have two forms on the same page that update different rows in the table on clicking the submit button, without redirecting to a different page?
Thank you
You could give each submit (or other input) a unique name, and check if it's set after POSTing
For example, give your submit button a name:
<input type="submit" name="turtle">
And in your PHP:
<?php
if(isset($_POST['turtle'])) {
// Process the form associated with the "turtle" submit button.
} else {
// Do the other form stuff.
}
?>
Why don't you combine into one form and check if the user has entered a password?
<?php
$con = mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit'])):
$email = mysqli_real_escape_string($_POST['Email']);
$password = mysqli_real_escape_string($_POST['Password']);
$ID = $_SESSION['ID'];
// Validate Email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$errors[] = "Please enter a valid Email Address";
}
// Check if the password field has been filled in
if($password) {
// If it has then do your regex...
if (!preg_match("/^[a-zA-Z0-9#_]*$/",$password)) {
$errors[] = "Please enter a valid password";
$update_password = false;
} else {
$update_password = true;
}
}
if(count($errors) == 0) {
// Update Email
$sql="UPDATE `customer`
SET `Email`='$email'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
// If the test above passed then update the password
if($update_password) {
$sql="UPDATE `customer`
SET `Password`='$password'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
}
echo 'Update Complete';
//header("Location: userpage.html");
}
?>
<?php else: ?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?> method="post"><br />
<?php if($errors): ?>
<span class="error">* <?php echo explode(', ',$errors);?></span><br /><br />
<?php endif; ?>
Email:<br /> <input type="text" name="Email" value="<?php echo $email;?>">
Password:<br /> <input type="password" name="Password">
<input type="submit" name="submit">
</form>
<?php endif; ?>
P.S I tidied up your code as it gave me a hernia.
Use hidden inputs to seperate requests
OR
Use seperate files for your different forms as targets...
OR
Use jboneca's answer
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.