I am trying to insert data from a form I have made into my MYsql table using mysqli but whenever I submit my form it just displays the successfully connected to db server. Any ideas? It should show my errors for the insert shouldn't it?
<?php
if ($_POST['submit']) {
$errormsg = "";
$name = $_POST['name'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$connection = #mysqli_connect("$hostname","$username", "$password", "$database");
if(!$connection){
die("<p>The database server is not available.</p>".mysqli_error());
}
echo "<p>Sucessfully connected to the database server.</p>";
if((!$name)||(!$password)||(!$password2)||(!$email)||(!$phone)){ /* Checks if all inputs are filled*/
$errormsg = "Please insert the required fields below<br />";
if ($name == "")
{
$errormsg = $errormsg . "Enter a name.<br />";
}
if ($password == "")
{
$errormsg = $errormsg . "Please enter a password.<br />";
}
if ($password2 =="")
{
$errormsg = $errormsg . "Please re-enter your password.<br />";
}
if ($email =="")
{
$errormsg = $errormsg . "Please enter an email address.<br />";
}
if ($phone =="")
{
$errormsg = $errormsg . "Please enter a phone number.<br />";
}
if($errormsg){
echo "$errormsg";
}
}
if($password != $password2) {
$errormsg = $errormsg. "Your passwords must match!<br/>";
}
function checkEmail($email){ //begin email check function
$sql = "SELECT count(email) FROM CUSTOMER WHERE email='$email'";
$result = mysqli_result(mysqli_query($sql),0);
if( $result > 0 ){
$errormsg = $errormsg. "There is already a user with that email!";
}//end email check function
if(!$errormsg)
{
$insertquery = "INSERT INTO CUSTOMER (customer_no, name, password, email, phone)
VALUES(NULL, '$name', '$password', '$email', '$phone')";
$queryresult = mysqli_query($insertquery);
if($queryresult)
{
echo("<br>Registration sucessful");
}
else
{
echo("<br>registration was not sucessful");
}
}
}
}
?>
May be this can work. You can try this:
<?php
if ($_POST['submit']) {
$errormsg = "";
$name = isset($_POST['name'])?$_POST['name']:NULL;
$password = isset($_POST['password'])?$_POST['password']:NULL;
$password2 = isset($_POST['password2'])?$_POST['password2']:NULL;
$email = isset($_POST['email'])?$_POST['email']:NULL;
$phone = isset($_POST['phone'])?$_POST['phone']:NULL;
//Try by removing #, since it ignores any error that may occur here while connecting to mysql
$connection = mysqli_connect("$hostname","$username", "$password", "$database");
if(!$connection)
die("<p>The database server is not available.</p>".mysqli_error());
echo "<p>Sucessfully connected to the database server.</p>";
if(empty($name)||empty($password)||empty($password2)||empty($email)||empty($phone))
{ // Checks if all inputs are filled
$errormsg = "Please insert the required fields below<br />";
if ($name == "")
$errormsg = $errormsg . "Enter a name.<br />";
if ($password == "")
$errormsg = $errormsg . "Please enter a password.<br />";
if ($password2 =="")
$errormsg = $errormsg . "Please re-enter your password.<br />";
if ($email =="")
$errormsg = $errormsg . "Please enter an email address.<br />";
if ($phone =="")
$errormsg = $errormsg . "Please enter a phone number.<br />";
if($errormsg)
echo "$errormsg";
}
if($password != $password2)
$errormsg = $errormsg. "Your passwords must match!<br/>";
function checkEmail($email)
{ //begin email check function
$sql = "SELECT count(email) FROM CUSTOMER WHERE email='$email'";
$result = mysql_result(mysqli_query($connection,$sql),0);//see the difference
if( $result > 0 )
$errormsg = $errormsg. "There is already a user with that email!";
}//end email check function
if(!$errormsg)
{
$insertquery = "INSERT INTO CUSTOMER (customer_no, name, password, email, phone)
VALUES(NULL, '$name', '$password', '$email', '$phone')";
$queryresult = mysqli_query($connection,$insertquery);//see the difference
if($queryresult)
echo("<br>Registration sucessful");
else
echo("<br>registration was not sucessful");
}
}
}
?>
You can learn more from here. Enjoy!
Related
i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>
Is it possible to split the Username or Email already exists into specific error messages?
I'm working on this user registration script, if you have any tips about the rest of code given would be much appreciated
if(isset($_POST['register'])){
if(
// check if posts not empty
empty($_POST['username']) ||
empty($_POST['email']) ||
empty($_POST['password']) ||
empty($_POST['re_password']) ||
$_POST['password'] != $_POST['re_password']
){
// if a field is empty, or the passwords don't match make a message
error = '<p>';
if(empty($_POST['username'])){
$error .= 'No username given<br>';
}
if(empty($_POST['email'])){
$error .= 'No email given<br>';
}
if(empty($_POST['password'])){
$error .= 'No password given<br>';
}
if(empty($_POST['re_password'])){
$error .= 'You must re-type your password<br>';
}
if($_POST['password'] != $_POST['re_password']){
$error .= 'Passwords don\'t match<br>';
}
$error .= '</p>';
}
else{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = $_POST['re_password'];
$query = mysqli_query(
$conn,"SELECT * FROM members WHERE username = '". $username ."' OR email = '". $email ."'");
if(mysqli_num_rows($query) > 0){
echo "Username or Email already exist";
}
else {
$sql = "INSERT INTO members (username, password, email)
VALUES
('$_POST[username]',
'$_POST[email]',
'$_POST[password]')";
if (mysqli_query($conn, $sql)) {
echo "Registered";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
}
if(isset($error)){
echo $error;
unset($error);
}
You need to change here only:--
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)){
if(isset($row['username']) && !empty($row['username']) && $_POST['username'] ==$row['username'] )){
echo "Username already exist";
}
if(isset($row['password']) && !empty($row['password']) && $_POST['password'] ==$row['password'] )){
echo "Password already exist";
}
}
}
Note:- if your password have some encryption then you need to change password part condition accordingly (just third part of it). Also if i missed any wher indexes in writing let me know.
I wrote the following code in baby steps, working with each thoroughly until it's worked. The last step was checking that a username/email does not exist and if true, inserting everything into a database. I got the code to send an email if there are not errors up until [5], but I cannot test anything beyond sending an email. When form is completed and sent, the page is cleared after the heading and does not proceed to the next page.
I have gone over the code as thoroughly as I possibly could, pulling up multiple sources and checking over general syntax with php validation tools. I don't have anything that comes up.
Connection:
$con = mysqli_connect('$db_host', '$db_user', '$db_pass', '$db_name');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Body:
if (isset($_POST['process'])) {
$birthday = $_POST['year'].$dash.$_POST['month'].$dash.$_POST['day'];
$user_name = htmlspecialchars($_POST['user']);
$email = htmlspecialchars($_POST['email']);
$pass = htmlspecialchars($_POST['pass']);
$confirm = htmlspecialchars($_POST['confirm']);
if ($_POST['user'] == '') {
$errors[1] = 'Please enter your username.';
} else if (!preg_match('/^[a-zA-Z0-9]{4,25}$/', $_POST['user'])) {
$errors[1] = 'Usernames must contain 4 to 25 alphanumeric characters.';
} else {
$errors[1] = '';
}
if ($_POST['email'] == '') {
$errors[2] = 'Please enter your email.';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[2] = 'Email must be valid.';
} else {
$errors[2] = '';
}
if ($_POST['pass'] == '') {
$errors[3] = 'Please enter your password.';
} else if (!preg_match('$\S*(?=\S{6,})\S*$', $_POST['pass'])) {
$errors[3] = 'Passwords must be at least six characters long.';
} else {
$errors[3] = '';
}
if ($_POST['confirm'] == '') {
$errors[4] = 'Please confirm your password.';
} else if ($_POST['confirm'] != $_POST['pass']) {
$errors[4] = 'Passwords do not match.';
} else {
$errors[4] = '';
$hash = password_hash ('$pass', PASSWORD_DEFAULT);
}
if (time() < strtotime('+13 years', strtotime($birthday))) {
$errors[5] = 'You are not at least thirteen years old.';
} else {
$errors[5] = '';
}
$to = $email;
$subject = 'Rabbit Showing and Breeding Association Registration Confirmation';
$header = 'From: RSBA Registration <registration#rsba.net>';
$message = 'Hello ' . $user_name . '!
You are receiving this email because you recently registered at Rabbit Showing and Breeding Association at http://rsba.net
Your confirmation code is: ' . $confirm_code . '
Please copy and paste the code into the account confirmation page or follow the following link to get started:
http://rsba.net/registration/confirmation.php?confirm_code=' . $confirm_code . '
Please disregard this email if you did not sign up for RSBA.
Thank-you,
Rabbit Showing and Breeding Association
This is an automated message. Do not reply.';
if ($errors[1] == '' && $errors[2] == '' && $errors[3] == '' && $errors[4] == '' && $errors[5] == '') {
$sentmail = mail($to,$subject,$message,$header);
}
if($sentmail){
include_once "../connect_info.php";
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '" . $user_name . "'");
$row = mysqli_fetch_array($result);
if ($row['user_name']) {
$errors[6] = 'This username already exists.';
}
$result = mysqli_query($con,"SELECT * FROM users WHERE email = '" . $email . "'");
$row = mysqli_fetch_array($result);
if ($row['email']) {
$errors[7] = 'A user is already registered with this email.';
}
if ($errors[6] == '' && $errors[7] == '') {
$result = "INSERT INTO users (user_name, email, hash, birthday, confirm_code, access_level)
VALUES ('$user_name', '$email', '$hash', '$birthday', '$confirm_code', '0')";
if (mysqli_query($con, $result)) {
header('Location:sent');
} else {
$error[8] = '<span class="error">You cannot be registered.</span>';
}
}
}
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 created registration form which sends a link via e-mail and you have to click it in order to be successfully registered, which makes you have to log in. The problem is that I can't log in, while everything else is working fine. Below you will find my register.php, activation.php and login.php. Any help would be great.
action = register.php
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}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[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
action = activation
if ($_GET['action'] == 'invitation') {
if (!empty($_GET['key'])){
//thelw na eleksw an afto to key uparxei sto tabale members
$sql = "SELECT * FROM members WHERE activationCode = '".$_GET['key']."'";
$result=mysql_query($sql,$lnk);
$user= mysql_fetch_assoc($result);
if(!empty($user)){
//edw tha energopoiisw ton xristi
$sql = "UPDATE members SET flag=1 WHERE username = '".$user['username']."'";
mysql_query($sql,$lnk);
}else{
echo "this is WRONG";
}
}else{
echo 'No key';
}
}
action = login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
you are doing wrong with password.
use below code
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}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[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = md5($_POST['password']);
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
and for login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = md5($_POST['password']);
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
I'm guessing the error is here:
action = login
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true)); // HERE
}
You've just changed your password into something completely random, then you are trying to look for it in the database...
The key to programming is understanding what you are doing and knowing methods to determine what is wrong. It is ALL about problem solving. As you can see in your code: (action = login)
else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
You generate a random password each time rather than hashing the password that was provided. You then go on to check if it exists with the user. You need to make it like your registration method:
$password = md5($_POST['password']);
Another problem you have is in your query to check for valid user. Your flag field is an int but you're treating it like a string.
AND flag = '1' ";
needs to be
AND flag = 1 ";
NOTICE: DO NOT USE MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO. You are also wide open for SQL injections, be careful.