0
I'm setting up the wholly organized sign up form, I'm trying to sent into information into my MySQL database server. My code not work and can't figuring out pops up message You have been signed up!
I've tried several options but none of them work on a server,
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
if (mysqli_connect_error()) {
die("There was an error connecting to the database");
}
if ($_POST['email'] == '') {
echo "<p>Email address is required.</p>";
} else if ($_POST['password'] == '') {
echo "<p>Password is required.</p>";
} else {
$query = "SELECT `id` FROM `users` WHERE email = '" . mysqli_real_escape_string($link, $_POST['email']) . "'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo "<p>That email address has already been taken.</p>";
} else {
$query = "INSERT INTO `users` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
}
}
}
?>
When I signed up form only pops up "There was a problem signing you up - please try again later" I want to expect to "you have been signed up" from the result .
here is the problem
Related
This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie
The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}
I am having problems sending info into my database in Corona SDK Lua . I was previously using the $_GET method but I was told that it's not safe so I switched to _POST and now i keep getting the else statement but my console log isn't showing any errors .
register.php:
// Check connection
if ($con->connect_error) {
die("Check connection.");
}
if(isset($_POST['Register'])) {
if ($_POST['pw'] == $_POST['pw2']) {
$username = mysqli_real_escape_string($con, $_POST["username"]);
$pw= mysqli_real_escape_string($con, $_POST["pw"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$result = mysqli_query($con ,"SELECT * FROM users WHERE username='" . $username . "'");
if(mysqli_num_rows($result) > 0)
{
echo "Username exist";
} else {
$result2 = mysqli_query($con ,"SELECT * FROM users WHERE email='" . $email. "'");
if(mysqli_num_rows($result2) > 0)
{
echo "email exist";
} else {
$sql = "INSERT INTO users (username, pw, email) VALUES('" . $username . "', '" . $pw . "', '" . $email . "')";
if(mysqli_query($con, $sql)){
// if insert checked as successful echo username and password saved successfully
echo"success";
}else{
echo mysqli_error($con);
}
} } }
}else{
echo "The passwords do not match."; // and send them back to registration page
}
register.lua:
local function userRegister( event )
if ( "ended" == event.phase ) then
if emptyFields() == true then
else
if passwordMatch() == true then
else
local URL = "http://hash.comxa.com/register.php?Register=1&username=" .. username.text .. "&pw=" .. pw.text .. "&pw2=" .. pw2.text .. "&email=" .. urlencode( email.text )
network.request(URL, "POST", networkListener)
end
end
end
end
local function networkListener( event )
if ( event.isError ) then
print( "Network error.")
else
if event.response == "success" then
-- put the code here to go to where the user needs to be
-- after a successful registration
composer.gotoScene("login")
else
-- put code here to notify the user of the problem, perhaps
-- a native.alert() dialog that shows them the value of event.response
-- and take them back to the registration screen to let them try again
local alert = native.showAlert( "Error Signing Up", "There was an error signing up.", { "Try again" } )
end
end
end
I have a form that passes input data to a processing page. This processing form then checks whether the email and user name already exists in the database. If they do, an error is reported, the function I am having difficulty with is, if the error reports nothing then go and execute the sql insert query otherwise echo the error. I can get most of it to work except the insert data to database. Can anyone help me see the error in my code please ?
Processing page :
<?php
session_start();
list($username,$email,$clubname, $hash) = $_SESSION['data'];
unset($_SESSION['data']);
include_once 'db_connect.php';
$usernameErr = $emailErr = "";
$password = $hash;
$databaseErr = 'cannot connect to database';
$query1 = mysqli_query($mysqli, "SELECT * FROM members WHERE email='".$email."'");
if(mysqli_num_rows($query1) > 0){
// echo 'email already exists';
$usernameErr = "username already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query1))
{
die('Error: ' . mysqli_error($mysqli));
}
}
$query2 = mysqli_query($mysqli, "SELECT * FROM members WHERE username='".$username."'");
if(mysqli_num_rows($query2) > 0){
// echo 'username already exists';
$emailErr = "email already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query2))
{
die('Error: ' . mysqli_error($mysqli));
}
}
if ($usernameErr == "" && $emailErr == "" ) {
$sql = mysqli_query($mysqli, "INSERT INTO members (username, email, password, clubname) VALUES ('$username', '$email', '$password', '$clubname')");
if (!mysqli_query($mysqli,$sql)) {
die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
}
else {
echo $usernameErr.'<br/><br/>';
echo $emailErr.'<br/><br/>';
}
I came up with this, a simple skeleton, just edit to suit you. Don't forget to hash the password parameter.
function emailEmailExists($emall) {
if(mysqli_num_rows($email) >= 1) {
return 1;
} else {
return 0;
}
}
function usernameExists($username) {
if(mysqli_num_rows($username) >= 1) {
return 1;
} else {
return 0;
}
}
function insertUser($username, $password, $email, $otherField, $otherField, ) {
if(checkEmailExists($email) == 1) {
echo 'Email in use!';
} else if(usernameExists($username) == 1){
echo 'Username in use!';
} else {
$insertUser = mysqli_query($yourQuery);
if($insertUser) {
echo 'User created!';
} else {
// Give error.
}
}
}
Edit
How do you create you DB connection, remove your credentials and please show.
This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie