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)";
Related
I'm having a problem with my php code, it seems that it returns "Password Should Not Be empty" when I do input a password. I think it might be coming from my html code because I make them input it twice. Do I need to make another variable in my database for confirm password?
<?php
$firstname = filter_input(INPUT_POST, 'firstname');
$lastname = filter_input(INPUT_POST, 'lastname');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
if (!empty($firstname)) {
if (!empty($lastname)) {
if (!empty($email)) {
if (!empty($password)) {
$host = "127.0.0.1:3307";
$dbusername = "root";
$dbpassword = "";
$dbname = "register";
// Create connection
$conn = new mysqli($host, $dbfirstname, $dblastname, $dbemail,
$dbpassword);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
} else {
$sql = "INSERT INTO Signup (firstname, lastname, email, password) values ('$firstname','$lastname','email','password')";
if ($conn->query($sql)) {
echo "New record is inserted sucessfully";
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
}
} else {
echo "Password should not be empty";
die();
}
}
}
} else {
echo "Username should not be empty";
die();
}
Your error is because your post value is $_POST['psw'], while your code is expecting $_POST['password']. Either change your HTML form, or your PHP code so that the values are the same.
Your code is very confusing. I made it a little simpler, try this and see if you still get the same error:
# Check to see if you're getting the right variables in the first place:
var_dump($_POST); //Remove once you're sure you're getting the right stuff
if(!$firstname = filter_input(INPUT_POST, 'firstname')){
die("First name should not be empty");
}
if(!$lastname = filter_input(INPUT_POST, 'lastname')){
die("Last name should not be empty");
}
if(!$email = filter_input(INPUT_POST, 'email')){
die("Email should not be empty");
}
if(!$password = filter_input(INPUT_POST, 'password')){
die("Password should not be empty");
}
$host = "127.0.0.1:3307";
$dbusername = "root";
$dbpassword = "";
$dbname = "register";
$conn = new mysqli($host, $dbfirstname, $dblastname, $dbemail, $dbpassword);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$sql = "INSERT INTO Signup (firstname, lastname, email, password) values ('$firstname','$lastname','email','password')";
if (!$conn->query($sql)) {
echo "Error: " . $sql . "\r\n" . $conn->error;
$conn->close();
exit;
}
echo "New record is inserted successfully";
General guidelines
Don't nest if() statements. It makes following code very confusing.
If a boolean outcome is a deal breaker, have that outcome first in the if/else statement. For instance if the SQL query fails, have the negative outcome first in the if() statement (which will stop your code), and skip the else statement all together.
Comment your code.
<form method="post" action="overstack.php">
<div class="container">
<br>
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstname"><b>First Name</b></label>
<input type="text" placeholder="Enter First Name" name="firstname" required>
<label for="lastname"><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="lastname" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
this is my html form for the php code above
My question is, how do I get the form to display an error when the user doesn't input a field into the form. I can get it to work when they don't fill out the form at all and just hit enter, but cannot get it to work if they only fill out a few fields. They could fill out the title field and the run time field and will be able to submit it. How can I get it to make sure that every field is filled out?
<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
if(isset($_POST['submit'])) {
$value = mysqli_real_escape_string($conn,$_POST['title']);
$value2 = mysqli_real_escape_string($conn,$_POST['rating']);
$value3 = mysqli_real_escape_string($conn,(int)$_POST['Runtime']);
$value4 = mysqli_real_escape_string($conn,(float)$_POST['movie_rating']);
$value5 = mysqli_real_escape_string($conn,$_POST['release_date']);
// Checks for empty fields
if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
echo 'Please correct the fields';
return false;
}
// Concatenate the $values into the string
$sql = "INSERT INTO movies(title,rating,Runtime,movie_rating,release_date)
VALUES('$value','$value2','$value3','$value4','$value5')";
if ($conn->query($sql)) {
$msg = "New record created successfully";
} else {
$msg = "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<form method="post"/>
<p>Enter Movie Title: <input type="text" name="title"/></p>
<p>Enter Movie Rating(G,PG,PG-13,R): <input type="text" name="rating"/></p>
<p>Enter Movie Runtime in minutes: <input type="text" name="Runtime"/></p>
<p>Enter IMDB Movie Rating(0-10.0): <input type="text" name="movie_rating"/></p>
<p>Enter Movie Release date(YYYY-MM-DD): <input type="text" name="release_date"/></p>
<button type="submit" name="submit">Submit</button
</form>
<?php
if (isset($msg)) {
echo $msg;
}
?>
From Front side you can add required attribute to each input. So add it in every input field like :
<input type="text" name="title" required/>
From back-end side (using PHP) If you want all value must be fill up then change && with || in your condition
// Checks for empty fields
if (empty($value) || empty($value2) || empty($value3) || empty($value4) || empty($value5)) {
echo 'Please correct the fields';
return false;
}
if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
echo 'Please correct the fields';
return false;
}
This should be 'or'
This question already has answers here:
Insert data only if record does not exist
(3 answers)
Closed 8 years ago.
Here's my form:
<section class="loginform tmr">
<form name="login" action="welcome.php" method="post" accept-charset="utf-8">
<label for="username">Username: </label><br />
<?php if (isset($input_errors['username'])) { echo '<div class="error">' . $input_errors['username'] . '</div>'; } ?>
<input type="username" name="username" placeholder="Handle" required><br />
<input type="hidden" name="sign_up_date" value="<?php echo $_POST['sign_up_date'] ?>">
<label for="usermail">Email: </label><br />
<?php if (isset($input_errors['usermail'])) { echo '<div class="error">' . $input_errors['usermail'] . '</div>'; } ?>
<input type="email" name="usermail" placeholder="yourname#email.com" required><br />
<label for="password">Password: </label><br />
<input type="password" name="password" placeholder="password" required><br />
<input type="submit" value="Login">
</form>
</section>
Here's all my validation on my insert:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
I want to check username and email and if either are in use than alert the new registration user...
I'm thinking that my server side validation stuff is getting so messy that maybe i should build a class for this...??
That's not necessarily something i need help with atm.. I really just want to check mysql using best practices if the email is in use or the username is in use..
Any and all help would be greatly appreciated. Thank you.
try below or follow link php mysqli check if any result exist
<?php
function user_exists($email) {
$query = "SELECT 1 FROM " . USER_TABLE . " WHERE email = ?";
$stmt = $this->_db->prepare($query);
$stmt->execute(array($email));
return (bool)$stmt->fetchColumn();
}
//do your stuff here same for username
if(user_exits($register_email))
This code selects the number of rows with either username or email:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}
I have a simple entry form which includes an email address. I want to check for a duplicate (which I can do) but what I'm struggling with is how to get the entry form to indicate it is a duplicate "Please Try Again".
The Entry Form code is as follows:
<form action="mailer2.php" method="POST">
<div>
<p class="auto-style1" style="width: 408px">Newsletter Sign-Up Form</p>
<p>First Name</p>
<input name="firstname" type="text"> <br> </div>
<div>
<p>Last Name</p>
<input name="lastname" type="text">
<br>
</div>
<p>E-Mail</p>
<input name="email" type="text">
<br>
</div>
<div>
<p>What are your interests"</p><br>
<input type="checkbox" name="activity[]" value="run">I enjoy running<br>
<input type="checkbox" name="activity[]" value="bike">
I enjoy mountain biking<br>
<input type="checkbox" name="activity[]" value="hike">I enjoy hiking<br>
</div>
<div>
<input name="submit" type="submit" value="Send!"> </div>
</form>
The PHP code: This is where I am stuck...how do I get back to my form and note below the email address it is a duplicate
<?php
$hostname = "hostname";
$username = "Username";
$password = "password";
$dbname = "Tablename";
$TableName = "MemberInfo";
// Check connections
mysql_connect($hostname, $username, $password) or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
// Get values from form
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$email=$_POST['email'];
$FullName = $fname . " " . $lname;
$activity=$_POST['activity'];
$run = 0;
$bike = 0;
$hike = 0;
//Check for Duplicate Email
$result = mysql_query("SELECT * FROM MemberInfo WHERE Email='$email'");
$DupCheck = mysql_num_rows($result);
if ($DupCheck) {
echo "Email already exists ... please try again.";
//header('Location: NewsletterSignUp.html');
exit;
//trigger_error('Email Already Exists.', E_USER_WARNING);
}
if (isset($_POST['activity'])) {
$activity = $_POST['activity'];
foreach($activity as $key => $value) {
//echo $key. ' = ' . $value . '<br>';
if ($value == 'run') {
$run = 1;
}
if ($value == 'bike') {
$bike = 1;
}
if ($value == 'hike') {
$hike = 1;
}
}
} else {
echo 'Nothing';
}
// Insert data into mysql
$sql="INSERT INTO $TableName (FirstName, LastName, FullName,
Email, Run, Bike, Hike) VALUES('$fname', '$lname',
'$FullName', '$email', '$run',
'$bike', '$hike')";
$result=mysql_query($sql);
// if successful insert data into database, displays message "Successful".
if($result){
header('Location: Confirmation.html');
}
else {
die('Invalid query: ' . mysql_error());
}
if(isset($_POST['submit'])) {
// Send email
$to = "someone#example.com";
$subject = "Newsletter Sign-Up";
// data the visitor provided
$fname_field = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$lname_field = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
foreach($_POST['activity'] as $value) {
$activity_field .= "Checked: $value\n";
}
//constructing the message
$body = " From: $fname_field $lname_field\n\n
E-Mail: $email_field\n\n$activity_field";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
<?php
// close connection
mysql_close();
?>
(edit - show form html)
The easiest way would be making email field as UNIQUE with index, then it will be no possible to add 2 same e-mail fields. The other way is to make select with this mail and check if there is record with this field.
Also don't use mysql_* functions they are old and will be removed in future.
here is more about unique index http://dev.mysql.com/doc/refman/5.0/en/create-index.html
In my personal experience I like to put a lot of things into database, if there is something that can be checked via database, why don't use it?
Make change into your Db
ALTER TABLE $TABLE
ADD UNIQUE INDEX Email(Email);
or
CREATE UNIQUE INDEX unique_email
ON $TABLE (Email)
adding new row where there is already email will return error or if you use pdo it will throw exception. Something like:
ERROR 1062 (23000): Duplicate entry 'xxx' for key 1.
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>