how do I create an SQL and PHP IF statement with else - php

I have created a if statement that is to check if a username is stored on the SQL database, I am not sure why when it checks the database it always finds that there is a username already inserted even when the database can be empty.
I have tried various variations of an if statement and I am not having much luck.
<?php
if(isset($_POST['save'])){
include 'includes/config.php';
$fname = $_POST['fname'];
$pass = $_POST['pass'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$location = $_POST['location'];
$check = "SELECT email FROM client WHERE email = '$email'";
$res_e = mysqli_query($db, $check);
if (mysqli_num_rows($res_e) == 0) {
echo "<script type = \"text/javascript\">
alert(\"Sorry... username already taken.\");
window.location = (\"signup.php\")
</script>";
} else {
$qry = "INSERT INTO `client`
VALUES('NULL','$fname','$email','$pass','$phone','$location','$gender',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL')";
$result = $conn->query($qry);
echo "<script type = \"text/javascript\">
alert(\"Successfully Registered. Proceed to Login.\");
window.location = (\"account.php\")
</script>";
}
}
I just need it to check if the username (email address) is stored and return that the username is already taken or if not already taken to insert the data into the database.

your're displaying the error if the email is not used (there's no user with this email)
if (mysqli_num_rows($res_e) == 0) {

Thanks for the comments, I noticed that I had a line of code missing:
$rws = $res_e->fetch_assoc();
And I changed the if statement to:
if ($rws == FALSE )
This has resolved my question.
Thanks again.

Related

Is there any other way of fixing this OTP verification problem?

Am making an verification system after the user signup he/she will be redirected to verify the with otp code. The code doesn't seem to work when i tried it out and displays no error to show.
<?php
include_once("__DIR__ . '/../connection/conn.php");
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$pass = mysqli_real_escape_string($conn, md5($_POST['password']));
$cpass = mysqli_real_escape_string($conn, md5($_POST['cpassword']));
$role = 'user';
$verification_status = '0';
$otp = mt_rand(1111,9999); //create 4 digits otp
$activation_code = rand(time(),10000000); //create a user unique id
$select_users = mysqli_query($conn, "SELECT * FROM `userssystem1` WHERE email = '$email' AND password = '$pass'") or die('query failed');
if(mysqli_num_rows($select_users) > 0){
$message[] = 'user already exist!';
}else{
if($pass != $cpass){
$message[] = 'confirm password not matched!';
}else{
mysqli_query($conn, "INSERT INTO `userssystem1`(username, email, password, role, otp, activation_code, verification_status) VALUES('$username', '$email' , '$cpass' , '$role', '$otp', '$activation_code' , '$verification_status')") or die('query failed to insert');
$message[] = 'registered successfully!';
header('location:verify.php?code='.$activation_code);
}
}
}
?>
After i copy the otp from the data table into the otp input field to make the necessary changes on the data table in the database, the verification_status is supposed to change to verified and otp code will be empty from the database table. `verification_status = 'verified'
<?php
//if user verified, so don't show verify page
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); error_reporting(E_ALL);
include_once("__DIR__ . '/../connection/conn.php");
if(isset($_POST['submit_otp'])){
if(isset($_GET['code'])){
$activation_code = $_GET['code'];
$otp = $_POST['otp'];
$sqlselect = "SELECT * FROM userssystem1 WHERE activation_code = '".$activation_code."'";
$resultSelect = mysqli_query($conn, $sqlselect);
if (mysqli_num_rows($resultSelect) > 0){
$rowSelect = mysqli_fetch_assoc($resultSelect);
$rowOtp = $rowSelect['otp'];
if ($rowOtp !== $otp) {
echo "<script>alert(Please provide correct OTP...!)</script>";
}else{
$sqlUpdate = "UPDATE userssystem1 SET otp = '', verification_status = 'verified' WHERE otp = '".$otp."' AND activation_code = '".$activation_code."'";
$resultUpdate = mysqli_query($conn, $sqlUpdate);
if ($resultUpdate){
echo "<script>alert(Your email has been verified)</script>";
header("Refresh:1; url=signup.php");
}else{
echo "<script>alert(Your email is not verify)</script>";
}
}
}
}
else{
header("Refresh:1; url=verify.php");
}
}
?>
Without seeing more of your code this is really just a guess, but you're checking for $_POST['submit_otp'] but then later down assign $otp to the value of $_POST['otp']. My guess is that maybe the first if (isset(... is coming back false because the $_POST key is wrong. Or, the second assignment is wrong and the SQL comes back with no rows.

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

Get id after insert and save it as value into another table

I am programming an App and I have a problem now.
When I register a new student with the app a Query runs on my php Script and insert the new student in my database.
What I want to do now is, when I am registering him, I want my php Script to run a multiple query so that all the other tables should be filled with NULL and the query should get the ID from the new created student to link it with the other tables(foreign key).
I tried it with mysqli_multiple_query and LAST_INSERT_ID() but both didn't work.
How would it be possible to get that id in return from my insert?
Here is my php script.
<?PHP
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown) VALUES('$Name','$Surname','$Street','$Hometown')";
$sql .= "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES ("","","","","",LAST_INSERT_ID())";
if(mysqli_multi_query($con,$sql)){
echo 'successfully registered';
} else {
echo 'oops! Please try again!';
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I hope someone can help me.
Don't concatenate the two queries. Execute the first, save the last id into a variable like
$id = mysqli_insert_id();
, then execute the second query referencing the variable among the values.
Be aware that if those $_POST variables come from a user submitted form it would be useful to do some validation on them before saving them into database. Maybe this answer would be a nice read ;)
I have modify your code. Try and see if it works for you.
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown)VALUES('$Name','$Surname','$Street','$Hometown')";
mysqli_query($con, $sql);
$id = mysqli_insert_id($con);
if ($id) {
$sql = "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES (NULL, NULL, NULL, NULL, NULL, $id)";
mysqli_query($con, $sql);
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>

What do I have to do to my code so it will only create the account if the email doesn't already exist in the Database? [duplicate]

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 8 years ago.
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
while ($myrow = mysql_fetch_array($result)) {
if ($email == $myrow['email']) {
$errorMessage = "Account with that email already exists";
} else {
$errorMessage = "Email doesn't match!";
}
}
if ($_POST['submit']) {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}
?>
When I fill in the form and hit submit it just inserts into the database even though the emails are the same. I tried putting the if statement with the submit button into the while loop but that didn't work either.
Use mysql_num_rows function to check weather the user already exist on the database or not. Use the code below
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
if(mysql_num_rows($result)==0){
if ($_POST['submit']) {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}
}
else
{
echo "the user with this email address already exist";
}
?>
Hope this helps you
You could change your condition to check whether or not the error message has been filled:
if ($_POST['submit'] && $errorMessage == "Email doesn't match") {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}

form validation through class

I am new to OOP. I want to use the values of class functions in a mySql query. But I am having difficulty retrieving the values. So maybe my method is not correct.
Below is my code and the result. As you can see, the echoed values are empty.
(If the attached code is not sufficient, then please let me know.)
Code:
if(isset($_POST['hidden']))
{
$validator = new FormValidator();
$fname =$validator->addValidation("fname","req","Please fill in First Name");
$email= $validator->addValidation("email","email","The input for Email should be a valid email value");
$lname= $validator->addValidation("lname","req","Please fill in Last Name");
$pass= $validator->addValidation("pass","req","Please fill in Password");
$con_pass= $validator->addValidation("confirmpass","req","Please fill in Confirm Password");
$sname= $validator->addValidation("sname","req","Please fill in Screen Name");
if($validator->ValidateForm())
{
echo $insert_query ="insert into registeration set fname = '".$fname."', lname = '".$lname."', email = '".$email."', pass = '".$pass."', cpass = '".$con_pass."', sname = '".$sname."' ";
mysql_query($insert_query);
Result:
insert into registeration set fname = '', lname = '', email = '', pass = '', cpass = '', sname = ''
Query you are using is more appropriate if you are updating an existing record try this
if($validator->ValidateForm())
{
$fname = $_POST['fname']; // name of your input field
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$con_pass = $_POST['con_pass'];
$sname = $_POST['sname'];
$insert_query = mysql_query("INSERT INTO registeration (fname,lname,email,pass,cpass,sname)
VALUES ('$fname','$lname','$email','$pass','$con_pass','$sname')") or die(mysql_error());
}
( edited ) and reason for not working is because your variables are equal to the instance of methods you are calling you need to make them equal to the input fields.
Hope this can help you

Categories