I am creating a simple login script using PHP and MySQL, no errors are coming up but for some reason the information submitted is just not being inserted into the database.
The database is named 'test' (Without quotes) and the table 'users' (Also without quotes).
The columns in the table are first_name, last_name, email, pass and registration_date.
Here is the html form:
<form action="script4.php" method="post">
<p>First Name:<input type="text" name="first_name" value="first_name" /></p>
<p>Last Name:<input type="text" name="last_name" value="last_name" /></p>
<p>Email: <input type="text" name="email" value="email" /></p>
<p>Password: <input type="password" name="pass1" value="pass1" /></p>
<p>Confirm Password: <input type="password" name="pass2" value="pass2"/></p>
<input type="submit" name="submit" value="register" />
</form>
and here is script4.php
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
require ('mysql_connect.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();}
if (!empty($_POST['first_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$fn = trim($_POST['first_name']);
}
if (!empty($_POST['last_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$ln = trim($_POST['last_name']);
}
if (!empty($_POST['email'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$e = trim($_POST['email']);
}
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = "Your passwords do not match.";
} else {
$p = trim($_POST['pass1']);}
}else {
$errors[] = "You forgot to enter your password.";
}
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users ('first_name', 'last_name', 'email', 'pass', 'registration_date') VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW()) or trigger_error('Query Error: ' . mysql_error());";
$r = #mysqli_query ($dbc, $q);
if ($r) {
echo("Thanks");
} else {
echo("We are sorry, you could not be entered at this time.");
echo mysqli_error($dbc);
} }
mysqli_close($dbc);
?>
I know this script is vulnerable to sql injection, it is just a test:)
The data will just not get submitted.
Remove the single quotes from the column names.
You are calling require ('mysql_connect.php') twice.
You had multiple syntax errors.
You were assigning variables but not calling them.
You tried to add $pass to the database instead of $pass1.
I cleaned your code.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$first_name = empty($_POST['first_name']) ? '' : trim($_POST['first_name']);;
$last_name = empty($_POST['last_name']) ? '' : trim($_POST['last_name']);;
$email = empty($_POST['email']) ? '' : trim($_POST['email']);;
$pass1 = empty($_POST['pass1']) ? '' : trim($_POST['pass1']);
$pass2 = $_POST['pass2'];
if (!$first_name) {
$errors[] = "You forgot to enter your first name!";
}
if (!$last_name) {
$errors[] = "You forgot to enter your first name!";
}
if (!$email) {
$errors[] = "You forgot to enter your first name!";
}
if ($pass1) {
if ($pass1 != $pass2) {
$errors[] = "Your passwords do not match.";
}
} else {
$errors[] = "You forgot to enter your password.";
}
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users (first_name, last_name, email, pass,registration_date) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass1'), NOW()) or trigger_error('Query Error: ' . mysql_error());";
$r = #mysqli_query ($dbc, $q);
if ($r) {
echo("Thanks");
} else {
echo("We are sorry, you could not be entered at this time.");
echo mysqli_error($dbc);
}
mysqli_close($dbc);
} else {
foreach ($errors as $error) echo $error . '<br>';
}
}
?>
Also, it will be wise to escape the $_POST data or even better - use a prepared statements as currently, you are volunerable to SQL injection.
Hope this helps!
Remove the ! in all your conditional statements:
if (!empty($_POST['last_name']))
Means "if last_name is NOT empty", because of the !. Which means that your script currently says "error" if the fields are NOT empty. And if the scripts says "error", then in the end it doesn't insert the values in the database.
It doesn't say "we are sorry" too, because this statement is inside your conditional if(empty($errors)). So if $errors is not empty, you directly go to the end of the script without displaying anything, but witout having inserted your values.
So what you should do, for instance, is this:
if (empty($_POST['first_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$fn = trim($_POST['first_name']);
}
And in the end:
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ($first_name, $last_name, $email, SHA1($pass), NOW());";
if (#mysqli_query ($dbc, $q)) {
echo("Thanks");
} else {
echo mysqli_error($dbc);
echo("We are sorry, there is a problem with the database connection.");
}
} else {
echo("We are sorry, there are errors in the values you entered.");
}
mysqli_close($dbc);
As the others said, be careful because you have to remove one of your require('mysql_connect.php').
Remove the first require ('mysql_connect.php');
and change the following line to something like this because you got wrong syntax for your query and your trigger_error
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW())";
$r = mysqli_query($dbc, $q) or trigger_error('Query Error: ' . mysqli_error($dbc));
Remove the # and change mysql_error to mysqli_error with link otherwise you won't get your error.
if(empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO `users` (`first_name`, `last_name`, `email`, `pass`, `registration_date`) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW())";
$r = mysqli_query ($dbc, $q);
if($r){
echo "Thanks";
}else{
echo "We are sorry, you could not be entered at this time.";
trigger_error('Query Error: ' . mysqli_error($dbc));
}
mysqli_close($dbc);
}
Also you should look into binding parameters so eliminate sql injections.
Related
I am getting into PHP/MySQL code and I've searched all over for a solution to this problem but no answers match my issue.
My code is very simple but I can't find whats causing this error
<?php
$servername = "localhost";
$username = "langalungalangalunga";
$password = "langalungalangalunga";
$dbname = "user_main";
$client_username = $client_password = $client_email = "";
$usernameErr = $passwordErr = $emailErr = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['username'])) {
$client_username = test_input($_POST['username']);
} else {
$usernameErr = "No input on UserName";
}
if (!empty($_POST['password'])) {
$client_password = test_input($_POST['password']);
} else {
$passwordErr = "No input on Password";
}
if (!empty($_POST['email'])) {
$client_email = test_input($_POST['email']);
} else {
$emailErr = "No input on Email";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
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 user_main (UserName, Password, Email)
VALUES ($client_username, $client_password, $client_email)";
// use exec() because no results are returned
$conn->exec($sql);
echo "<script> alert('Success!');</script>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
The error points at line 2 of the email part
check the manual that corresponds to your MySQL server version for the right syntax to use near ' , email#email.com)' at line 2
<form class="" action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>' method="post">
<label for="username">Username</label>
<input type="text" name="username" value="<?php echo htmlspecialchars($_SERVER['username']) ?>">
<label for="password">Password</label>
<input type="password" name="password" value="">
<label for="email">Email</label>
<input type="email" name="email" value="">
<button type="submit" name="button">Register</button>
</form>
I am sorry if it's my mistake somewhere but I am new to PHP all together so I dont really have a feel for the syntax
$sql = "INSERT INTO user_main (`UserName`, `Password`, `Email`)
VALUES ('$client_username', '$client_password', '$client_email')";
$conn->query($sql);
The above code is vulnerable to SQL injection. Use prepared statements as
$stmt = $conn->prepare("INSERT INTO user_main (`UserName`, `Password`, `Email`)
VALUES (:UserName, :Password, :Email)");//placeholders
$stmt->bindParam(':UserName', $client_username);//you do not need to escape inputs
$stmt->bindParam(':Password', $client_password);
$stmt->bindParam(':Email', $client_email);
if($stmt->execute() == true){
//all good
echo'Data successfully saved Securely!';
} else {
print_r($stmt->errorInfo());
exit;
}
An extra tip. Do not store your passwords in plain text. Use password_hash
$hashedPassword = password_hash($client_password, PASSWORD_DEFAULT);
On checking if the password matches the hash, use password_verify
if(password_verify($client_password, $hashedPassword)){// do this when logging in or during some other authentication
//all good
echo 'Password is Correct';
} else {
echo 'Password is InCorrect.Sorry';
}
change you insert sql code like below:
Try this:
$sql = "INSERT INTO user_main (UserName, Password, Email)
VALUES ('".$client_username."', '".$client_password."', '".$client_email."')";
This is the html form (register.php):
<html>
<body>
<form action="handle_registration.php" method="post">
<fieldset><legend>Enter your
information in the form below:</legend>
First Name: <input type="text" name="fname" size="20" maxlength="40"><br>
Last Name: <input type="text" name="lname" size="20" maxlength="40"><br>
Username: <input type="text" name="uname" size="20" maxlength="40"><br>
Password: <input type="text" name="pword" size="20" maxlength="40"><br>
<input type="submit" name="submit" value="submit my info">
</form>
</body>
</html>
This is the php script that handles the registration (handle_registration.php):
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "registration_info";
$con = mysqli_connect("$db_host", "$db_user", "$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Make sure all of the input boxes have a value:
if (empty($fname)) {
die('You forgot to enter your first name!');
}
if (empty($lname)) {
die('You forgot to enter your last name!');
}
if (empty($uname)) {
die('You forgot to choose a username!');
}
if (empty($pword)) {
die('You forgot to choose a password!');
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);
?>
Here's the problem:
I want to submit the entered values into my database if all of the input fields have a value, but when I use the die function after checking to see if they're empty, then it kills the script. I just want to kill the part were it inserts it into my database if one or more of the fields are empty & display an error message that tells which field was empty. I'm not sure how to get around this and any help will be greatly appreciated.
The solution is rather simple. Just store the error message in a variable and before inserting rows into the DB - check weather the error is set or if it's empty. If it's empty - we can insert the row. Otherwise - let's show the error message.
// Currently we do not have an error
$error = NULL;
// Validate
if (empty($pword)) {
$error = 'You forgot to choose a password!';
}
// If there are no errors - lets insert
if (!$error) {
$sql = 'INSERT INTO ...';
}
DOn't use die ,use some variable to store errors and print them later
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname']; $lname = $_POST['lname']; $uname =
$_POST['uname']; $pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name =
"registration_info"; $con = mysqli_connect("$db_host", "$db_user",
"$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ()) { echo "Failed to connect to MySQL: " .
mysqli_connect_error(); }
// Make sure all of the input boxes have a value:
if (empty($fname)) { $error_msg[]='You forgot to enter your first name!'; }
if (empty($lname)) { $error_msg[]='You forgot to enter your last name!'; }
if (empty($uname)) { $error_msg[]='You forgot to choose a username!'; }
if (empty($pword)) { $error_msg[]='You forgot to choose a password!'; }
// Insert the data from the form into the DB:
if(count($error_msg)==0){
$sql = "INSERT INTO basic_information (First_Name, Last_Name,
Username, Password) VALUES ('$_POST[fname]', '$_POST[lname]',
'$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
else { echo "Record has been added"; }
// Close the connection:
mysqli_close($con);
}else{
print_r($error_msg);
}
?>
Full working example to stop insertion of empty data
<?php
if (isset($_POST["submit"])) {
$emptyInput = NULL;
if (!($_POST["firstname"] == $emptyInput or $_POST["lastname"] == $emptyInput or $_POST["email"] == $emptyInput)) {
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["email"] . "')";
if (mysqli_query($conn, $sql)) {
echo 'Record inserted successfully!';
}
} else {
echo 'all fields are compulsory!';
}
}
?>
You could use a $errors variable to hold the errors with all the fields
$error = array();//initializing the $error
if (empty($fname)) {
$error[] = 'You forgot to enter your first name!';
}
if (empty($lname)) {
$error[] = 'You forgot to enter your last name!';
}
if (empty($uname)) {
$error[] = 'You forgot to choose a username!';
}
if (empty($pword)) {
$error[] = 'You forgot to choose a password!';
}
if(!empty($error))//if error occured
{
die(implode('<br />', $error));//Stops the script and prints the errors if any occured
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);
Following is the PHP code
Database file working fine.
if(isset($_POST['submit']))
{
$error = array();
if(empty($_POST["fname"]))
{
$error[] = "Please Enter a name";
}
else
{
$fname = $_POST["fname"];
}
if(empty($_POST["lname"]))
{
$error[] = "Please Enter last name";
}
else
{
$lname = $_POST["lname"];
}
if(empty($_POST["email"]))
{
$error = "Enter email Id";
}
else
{
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0- 9\._-]+)+$/", $_POST["email"]))
{
$email = $_POST["email"];
}
else
{
$error = "Enter a vaild Email Id";
}
}
if(empty($_POST["password"]))
{
$error = "Enter a password";
}
else
{
$password = $_POST["password"];
}
if(!empty($error))
{
$sql = "SELECT * FROM form (id, 'FirstName', 'LastName', 'Email', 'Password') VALUES('', '$fname', '$lname', '$email', '$password')";
$result = mysql_query($sql);
echo "Successfully Register";
}
else
{
foreach($error as $key => $values)
{
echo ' <li>' . $values . '</li>';
}
echo '</ol>';
echo "Error";
}
}
?>
The above code is not displying any error messages... if i submit the form only blank page ll appear... I validate my form using above code but it is just a basic method I used and by using for each I'm displaying errors...
the following test is wrong :
if(!empty($error))
should be :
if(empty($error))
And your SQL is wrong too... should be :
$sql = "Insert into form (FirstName, LastName, Email, Password) VALUES('$fname', '$lname', '$email', '$password')";
supposing your id field is auto-incremented
You forget to push the errors to array. You have
$error = "Enter a password"; //$error is no more an array. It is a string
And must be in several places:
$error[] = "Enter a password";
Also, I recommend you using nested if statements:
if (!empty($_POST['submit'])){
$errors = array() ;
if (!isset($_POST['email'])
$errors['email'] = "No email" ;
//And so on.
//Then check for errors
if (!empty($errors)){
//proceed submission
}
}
Try This code, it will works fine for you.
<?php
if(isset($_POST['submit']))
{
$error = array();
if(empty($_POST["fname"]))
{
$error[] = "Please Enter a name";
}
else
{
$fname = $_POST["fname"];
}
if(empty($_POST["lname"]))
{
$error[] = "Please Enter last name";
}
else
{
$lname = $_POST["lname"];
}
if(empty($_POST["email"]))
{
$error[] = "Enter email Id";
}
else
{
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0- 9\._-]+)+$/", $_POST["email"]))
{
$email = $_POST["email"];
}
else
{
$error[] = "Enter a vaild Email Id";
}
}
if(empty($_POST["password"]))
{
$error[] = "Enter a password";
}
else
{
$password = $_POST["password"];
}
if(count($error)<=0)
{
$sql = "SELECT * FROM form (id, 'FirstName', 'LastName', 'Email', 'Password') VALUES('', '$fname', '$lname', '$email', '$password')";
$result = mysql_query($sql);
echo "Successfully Register";
}
else
{
foreach($error as $key => $values)
{
echo ' <li>' . $values . '</li>';
}
echo '</ol>';
echo "Error";
}
}
?>
I have a registration form that has some required field. i want to check if those required fields are filled and if they are filled correctly before i insert in my database.
One of the required field is email, i also want to check if the email entered is a valid email.
My code is below.
Thanks in advance for your help, i really appreciate it.
<?php
include 'config.php';
$tbl_name="citizens"; // Table name
// Get values from form and formatting them as SQL strings
$firstname = mysql_real_escape_string($_POST['firstname']);
$middlename = mysql_real_escape_string($_POST['middlename']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$sex = mysql_real_escape_string($_POST['sex']);
$address = mysql_real_escape_string($_POST['address']);
$employer = mysql_real_escape_string($_POST['employer']);
$posincom = mysql_real_escape_string($_POST['posincom']);
$states = mysql_real_escape_string($_POST['states']);
$agerange = mysql_real_escape_string($_POST['agerange']);
$income = mysql_real_escape_string($_POST['income']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "You Have Successful Registered";
}else {
echo "Sorry!!! Could Not Register You. All a* fields must be field.";
}
?>
<?php
include 'config.php';
$tbl_name="citizens"; // Table name
$required = array('email');
$errors = array();
foreach($required as $required_fieldname){
if(!isset($_POST[$required_fieldname]) || empty($_POST[$required_fieldname])){
$errors[] = 'Sorry!!! Could Not Register You. All a* fields must be field.';
break;
}
}
if(isset($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$errors[] = "That is not a valid email address.";
}
if(count($errors) == 0){
// Get values from form and formatting them as SQL strings
$firstname = mysql_real_escape_string($_POST['firstname']);
$middlename = mysql_real_escape_string($_POST['middlename']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$sex = mysql_real_escape_string($_POST['sex']);
$address = mysql_real_escape_string($_POST['address']);
$employer = mysql_real_escape_string($_POST['employer']);
$posincom = mysql_real_escape_string($_POST['posincom']);
$states = mysql_real_escape_string($_POST['states']);
$agerange = mysql_real_escape_string($_POST['agerange']);
$income = mysql_real_escape_string($_POST['income']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result= mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "You Have Successfully Registered";
}else {
echo "A technical error has occured.";
}
}
else{
echo '<strong>ERRORS!</strong><br>';
foreach($errors as $error){
echo $error . '<br>';
}
}
?>
you should validate form before submitting at client side using JavaScript, and alert to user if not filled correctly. Once validated allow it to submit .
In other case it is overhead to validate at server and than again send response to user at client end.
<?php
include 'config.php';
$tbl_name="citizens"; // Table name
// Get values from form and formatting them as SQL strings
//your other fields ...
$email = mysql_real_escape_string($_POST['email']);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors = 1;
echo "Please enter a correct email address";
}
//similar approach can be used for other fields..
// this is one of the simplest validating approach
if($errors == 0){
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "You Have Successful Registered";
}else {
echo "Sorry!!! Could Not Register You. All a* fields must be field.";
}
}
?>
For email you can use this (or similar) functions from https://stackoverflow.com/questions/3314493/check-for-valid-email-address to validate email
function isValidEmail($email){
return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
}
Or
function isValidEmail( $email ){
return filter_var( $email, FILTER_VALIDATE_EMAIL );
}
For the rest, you can use the following
<?php
$error = '';
//put chosen function here
function isValidEmail( $email ){
return filter_var( $email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$firstname = mysql_real_escape_string($_POST['firstname']);
if(!$firstname){ $error .= "First name is required<br />"; }
//repeat for each field
$email = mysql_real_escape_string($_POST['email']);
if(!isValidEmail($email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
}
else{
//display $error however you want e.g....
echo "<div class=\"error\">$error</div>";
}
?>
1.) you can use PHP_FILTER for validation.
2.) you can proper check( variable is null or not) before insert the data if variable is null the display error msg otherwish insert..
it validates and displays the errors in my arrays properly, however it doesn't POST to my database. All the naming of fields is correct on the form (case correct too), PHP, and MYSQL, dbconnect.php are all correct and proper. The problem i believe is somewhere in the array function. Now I just started learning PHP this month so please go easy on me. Thanks for the help!
<?php
include ('scripts/dbconnect.php');
$Name = mysql_real_escape_string($Name);
$Email = mysql_real_escape_string($Email);
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['Name'])) {//if no name has been supplied
$error[] = 'Please Enter Your Name ';//add to array "error"
} else {
$Name = $_POST['Name'];//else assign it a variable
}
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) { //regular expression for email validation
$Email = $_POST['Email'];
} else {
$error[] = 'Your EMail Address is Invalid ';
}
}
if (empty($error)) //Send to database if no errors
mysql_query("INSERT INTO InviteRequestDB ( 'Name', 'Email' ) VALUES ( '$Name', '$Email' )");
mysql_close($connect); //Close connection to database
foreach ($error as $key => $values) {
echo "<li style=color:#FFF> $values </li>";
}
?>
Now I know I shouldn't be using mysql. But I ran into too many problems with mysqli and this is just a simple contact form.
Also should I be doing mysql_real_escape_string on each variable as i am doing now? Or is the order of the procedure not correct?
<form action="applyforinvite.php" method="post">
<input class="textbox" type="text" name="Name" />
<input class="textbox" type="text" name="Email" />
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" />
</form>
Thanks for the help!
You shouldn't quote the column names in the INSERT query. ('name, 'email') should be (name, email).
Also, don't use the php_mysql extension for new applications, it's deprecated. Try MySQLi or PDO.
Final edit( lol ), try this -- fixed the multiple issues with the code:
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (empty($_POST['Name'])) { //if no name has been supplied
$error[] = 'Please Enter Your Name '; //add to array "error"
} else {
$Name = mysql_real_escape_string($_POST['Name']); //else assign it a variable
}
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) { //regular expression for email validation
$Email = mysql_real_escape_string($_POST['Email']);
} else {
$error[] = 'Your EMail Address is Invalid ';
}
if (empty($error)) //Send to database if no errors
{
mysql_query("INSERT INTO InviteRequestDB (Name, Email) VALUES ( '$Name', '$Email' )");
}
}
mysql_close($connect); //Close connection to database
foreach ($error as $key => $values) {
echo "<li style=color:#FFF> $values </li>";
}
Change
mysql_query("INSERT INTO InviteRequestDB ( 'Name', 'Email' ) VALUES ( '$Name', '$Email' )");
To
mysql_query('INSERT INTO InviteRequestDB ( Name, Email ) VALUES ( "'.$Name.'", "'.$Email.'" )') or die(mysql_error());
EDIT
<?php
include ('scripts/dbconnect.php');
if(isset($_POST['formsubmitted'])){
# Will contain errors
$Error = array();
# Email
$Email = (isset($_POST['Email']) ? $_POST['Email'] : '');
if($Email == '' OR !preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $Email)){
$Error[] = 'Email address is invalid.';
}
# Name
$Name = (isset($_POST['Name']) ? $_POST['Name'] : '');
if($Name == ''){
$Error[] = 'Please enter your name.';
}
if(count($Error)){
echo '<ul>';
foreach($Error as $Value){
echo '<li style="color: #FFF;">'.$Value.'</li>';
}
echo '</ul>';
} else {
// Query
mysql_query('INSERT INTO InviteRequestDB ( Name, Email ) VALUES ( "'.$Name.'", "'.$Email.'" )') or die(mysql_error());
}
//Close connection to database
mysql_close($connect);
}
?>
<?PHP
require_once('scripts/dbconnect.php');
if (!$link) { //Change $link to be your connection variable
die("Not connected : " . mysql_error());
}
if (!$db_selected) { //Change $db_selected to be the variable you set mysql_select_db on
die ("Can't use database : " . mysql_error());
}
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['Name'])) {//if no name has been supplied
$error[] = 'Please Enter Your Name ';//add to array "error"
} else {
$Name = mysql_real_escape_string($_POST['Name']);//else assign it a variable
}
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) { //regular expression for email validation
$Email = mysql_real_escape_string($_POST['Email']);
} else {
$error[] = 'Your EMail Address is Invalid ';
}
if (count($error) == 0){ //Send to database if no errors
mysql_query("INSERT INTO `InviteRequestDB` (`Name`, `Email`) VALUES('$Name', '$Email')")or die(mysql_error());
} else {
foreach ($error as $key => $values) {
echo "<li style=color:#FFF> $values </li>";
}
}
mysql_close($connect); //Close connection to database
}