Validation for username not working - php

I have written this code , its working to add users but for duplicate user it again saved the value os same user name. i wanted to give popup message if username already taken. i m beginner please help.
<?php
ob_start();
include("db.php");
if(isset($_POST['send'])!="") {
$username = mysqli_real_escape_string($con, $_POST['username']);
$usermail = mysqli_real_escape_string($con, $_POST['usermail']);
$usermobile = mysqli_real_escape_string($con, $_POST['usermobile']);
$bool = true;
$con = mysqli_connect("localhost","root","","demo");
$result = mysqli_query("SELECT `username` FROM `sample` WHERE username = '$username'");
if(mysqli_num_rows($result)>0)
{
Print '<script>alert("Username has been taken!");</script>';
}
if ($bool) {
$inssql = "insert into sample set
username = '" . $username . "',
emailid = '" . $usermail . "',
mobileno = '" . $usermobile . "',
created = now()";
$update = mysqli_query($con, $inssql);
}
}

Make sure you finish the script or turn off your flag before making the insert:
if(mysqli_num_rows($result)>0)
{
Print '<script>alert("Username has been taken!");</script>';
die('username already taken');
//$bool = FALSE;
}
If you still having duplicate entries, debug what is the result of $username and compare it with the value in the database.

Related

The value is not inserting in database

I want to create an API for registration with OTP verification. The OTP is successfully sent on mobile. But the value of users is not inserted in the database. Here is my signup code.
signup.php
<?php
include('config.php');
if( !empty($_POST['name']) &&
!empty($_POST['mobile']) &&
!empty($_POST['email']) &&
!empty($_POST['password'])
){
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$password = $_POST['password'];
$str = mt_rand(100000, 999999);
$avalible_user_name="";
$avalible_user_email="";
$SQL= mysql_query("SELECT * FROM users WHERE mobile='".$mobile."' ");
while($row=mysql_fetch_array($SQL)){
$avalible_user_name=$row['mobile'];
}
$SQL= mysql_query("SELECT * FROM users WHERE email='".$email."' ");
while($row=mysql_fetch_array($SQL)){
$avalible_user_email=$row['email'];
}
if($avalible_user_name=="" && $avalible_user_email==""){
$SQLQUERY = mysql_query("INSERT INTO users SET
name = '" . $name."',
mobile = '" . $mobile."',
email = '" . $email."',
password = '" . md5($password)."',
otp = '".$str."',
status = 0 ");
$msg = "Your verification code:".$str.".";
$sms_text = str_replace(" ","%20",$msg);
$api_key = '2584909553545C';
$from = 'chkotp';
$api_url = "**My otp url**";
$response = file_get_contents($api_url);
die(json_encode(array("success"=>"true","message"=>"OTP sent to your mobile number please verify.")));
}else{
die(json_encode(array("success"=>"false","message"=>"Mobile or email all ready exits ")));
}
}else{
die(json_encode(array("success"=>"false","message"=>"Empty Parameters..!!")));
}
?>
Your insert query syntax is wrong,
$new_pass = md5($password);
$SQLQUERY = mysql_query("INSERT INTO users( name, mobile, email, password) values('$name','$mobile','$email','$new_pass')");
I hope it helps.

MySql update query not updating data

I have a simple query which updates the last time a user logs in. For some reason, it is not updating the data when a user logs in. I would be grateful if someone could point out my error. Thanks
<?php
session_start();
$message="";
if(count($_POST)>0) {
$username_usr = $_POST["user_name"];
$password_usr = md5($_POST['password']);
$conn = mysql_connect("localhost","root","");
mysql_select_db("logistor_logistor",$conn);
$result = mysql_query("SELECT * FROM user_usr WHERE username_usr='" . $username_usr . "' and password_usr = '". $password_usr ."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["username"] = $row[username_usr];
$_SESSION["password"] = $row[password_usr];
$_SESSION["S_name"] = $row[name_usr];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["username"])) {
$query = "UPDATE user_usr SET logincounter_usr = logincounter_usr+1, lastlogin_usr = NOW() WHERE username_usr = '". $_SESSION["username"] ."'";
header("Location:user_dashboard.php");
}
?>
you miss execute the query in update
$query = "UPDATE user_usr SET logincounter_usr = logincounter_usr+1, lastlogin_usr = NOW() WHERE username_usr = '". $_SESSION["username"] ."'";
$result = mysql_query($query);

PHP username already exists, when it doesn't

I've checked many threads about my problem, but it still won't work.
When I enter username, which doesn't exist, it will throw the username has been created yet. But, when I enter an username already registered in my db, it still register.
Here is my php/html page for register :
$error = false;
if(isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
$query = mysqli_query($sql);
if(mysql_num_rows($query)){
$error = true;
$ckname_error = "Nom d'utilisateur déjà enregistré!";
} else { unset($ckname_error); }
if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,mail,password,rank) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "', 'user' )")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
header("Location: login.php");
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
You're getting unreliable results because you're mixing mysqli_ with mysql_ functions.
1. Change:
$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
to:
$sql = "SELECT name FROM users WHERE name='$name'";
2. Change
$query = mysqli_query($sql);
to:
$query = mysqli_query($con,$sql);
3. Change
if(mysql_num_rows($query))
to:
if(mysqli_num_rows($query))
You missed $con, and use mysqli_num_rows not mysql_num_rows
$query = mysqli_query($con,$sql);
if(mysqli_num_rows($query)){
You're using mysqli_query($sql). You should have used 'mysqli_num_rows()' instead of mysql_num_rows().
PHP reference - mysqli_num_row
int mysql_num_rows ( resource $result ) expects resource type, whereas if you're using mysqli_query, you should have used int mysqli_num_rows ( mysqli_result $result ) - expects mysqli_results.
Let us know if it works.

PHP update table using MySQL

I have student table in my DB , and I need to create extra form in student page so he can update the details. However im getting this error ( Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\wamp\www\WebInterfaceLogIn\studentEdit.php on line 81)
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
include ('includes/connection.php');
// Create connection
if (isset($_POST["submit"]))
{ //Determine if a variable is set and is not NULL.
if (!empty($_POST['ID']) && !empty($_POST['user']) && !empty($_POST['surr']) && !empty($_POST['course']) && !empty($_POST['mail']) && !empty($_POST['pass']))
{ //Determine if user enters both user name and password.
$ID = $_POST['ID']; // enters user ID in database
$user = $_POST['user']; // enters user name in database
$surr = $_POST['surr']; // enters user surname in database
$course = $_POST['course']; // enters user course in database
$pass = $_POST['pass']; // enters password in database
$mail = $_POST['mail'];
// $query = mysqli_query($con,"SELECT * FROM students WHERE Student_ID='".$ID."'"); // change to update
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");
$numrows = mysqli_num_rows($query);
if ($numrows == 0)
{
$sql = "INSERT INTO students(Student_ID,Name,Surname,Course,email,password) VALUES('$ID', '$user','$surr','$course','$mail','$pass')"; // insert user name and password to database
$result = mysqli_query($con, $sql);
// Checks does user enters the details
if ($result)
{
echo '<script language="javascript">;
alert("Account Successfully Updated");
document.location.href="index.php";
</script>';
}
else
{
echo mysqli_error($con);
}
}
}
else
{
echo '<script language="javascript">
alert("All fields required")
</script>';
}
}
Can anyone can help to solve this problem?
You need pass connection object to function mysqli_query, something like this:
mysqli_query($con,"UPDATE students SET `course` = " .$_POST['course']. ", `email` = " .$_POST['mail']. " Student_ID='".$ID."'");
See more details on:
http://www.w3schools.com/php/func_mysqli_query.asp
The error is explicit enough.
add $con as a first parameter to your mysqli_query function on this line:
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");

$_Post registration with variable return on registration status

So I'm trying to make a registration page that feeds back a variable when a certain flag is raised.. "All ready registered" "Registration limit" IS this the best way to do this or is there a better way? I'm a little new to PHP...I keep getting an error on the mysql_num_rows()..
Here is the code....
<?php
//not really
$dbhost = 'sample';
$dbname = 'contacts';
$dbuser = 'sample';
$dbpass = 'sample';
//retrieve our data from POST
$username = $_POST['username'];
$pass1 = $_POST['password'];
$pass2 = $_POST['timestamp'];
$pass3 = $_POST['deviceId'];
$pass4 = $_POST['phone'];
$pass5 = $_POST['name'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname, $conn);
//sanitize username
$username = mysql_real_escape_string($username);
$pass1 = mysql_real_escape_string($pass1);
$pass2 = mysql_real_escape_string($pass2);
$pass3 = mysql_real_escape_string($pass3);
$pass4 = mysql_real_escape_string($pass4);
$pass5 = mysql_real_escape_string($pass5);
function email_exists()
{
// $query = "SELECT * FROM Users WHERE username = '" . $username . "'";
$sql2 = mysql_query("SELECT username FROM Users WHERE username = '" . $username . "'");
// $sql2 = mysql_db_query("SELECT * FROM Users WHERE username = '" . $username . "'");
// $erg = mysql_num_rows($sql2) > 0;
return (mysql_num_rows($sql2)); //method 1
}
function device_exists()
{
$query2 = "SELECT * FROM Users WHERE deviceID = '" . $pass3 . "'";
//$sql2 = mysql_db_query("SELECT * FROM Users WHERE deviceID = '" . $pass3 . "'");
$sql3 = mysql_query($query2);
return (mysql_num_rows($sql3)); //method 2
}
if (email_exists() == 0) {
//(passed the no email in database, now lets check how many accounts under the device ID)
if (device_exists() < 3) {
$query = "INSERT INTO Users ( username, password, timestamp, deviceId, phone, name )
VALUES ( '$username' , '$pass1' , '$pass2', '$pass3', '$pass4', '$pass5');";
mysql_query($query);
mysql_close();
echo "1"; // Regstered succefully
} else {
echo "5"; //3 registered users per device only
}
} else {
echo "0"; //already have an account (email is used.....)
}
?>
You have may be same problem
Hello please try with the greaterthan operator (>) with zero
if ( email_exists()) // valid result
{
if ( email_exists() > 0 ) // more than 0 records
// rest code;
else
// insert operation;
}
Thanks... best luck

Categories