Check if already a user then insert into the database php - php

My code works, if I wish to insert into the database, but my checking whether the user already exists doesn't work.
*I thought the idea was to check if a row exists already with that username, if so don't add that user to the database, else
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$result = mysqli_query($mysqli, "SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1){
echo'User exists';
}else{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}

You have mixed the Procedural style & Object oriented style for executing the query.
When using,
1) Procedural Style
$result = mysqli_query($mysqli, "Your Query");
use this, $row_count = mysqli_num_rows($result);
2)Object oriented style
$result = $mysqli->query("Your Query");
Use this, $row_count = $result->num_rows;
So, According to your code, You are using Object Oriented Style. So, you need to change
$result = mysqli_query($mysqli,"SELECT username FROM users WHERE username = '$username'");
to
$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
Edited Code.
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1)
{
echo 'User exists';
}
else
{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute())
{
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}
else
{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
For more info, check this mysqli_num_rows vs ->num_rows

$db = ("SELECT username FROM userlist WHERE username='$username'");
$query = $conn->query($db);
if(mysqli_fetch_array($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}

Related

PHP echo all data from database based on input

I want to find out how to output data from database based on a single key,for example my database column are :
kodeDosen(PrimaryKey),namaDosen,email,telepon,password
and my login screen the user can only input kodeDosen and password,and i want to show the other data exept password,this is my register php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$namaDosen = $data["namaDosen"];
$email = $data["email"];
$telepon = $data["telepon"];
$password= $data["password"];
$message = array("message"=>"Success");
$failure = array("message"=>"Failure,kodeDosen already used");
$sql = "INSERT INTO tbl_dosen (kodeDosen, namaDosen, email, telepon, password) VALUES ('$kodeDosen', '$namaDosen', '$email', '$telepon','$password')";
if (mysqli_query($conn, $sql)) {
echo json_encode($message);
} else {
echo json_encode($failure) ;
}
?>
and this is my login php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
It's not a good idea to insert a variable directly into an SQL query because of SQL injection.
I would suggest to use prepared statements on both of the queries. To pull the result from the db with prepared statements it's something like:
OOP style:
$stmt = $db->prepare("SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
$stmt->bind_param('ss', $kodeDosen, $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
Procedural style:
$stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $kodeDosen, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
You can change in sql SELECT statement in login.php
$sql = "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";
in SELECT * means return all columns.
I think you want echo json_encode($row); rather than echo json_encode($message);
Try:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc( $result );
if(mysqli_num_rows($result) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>

Inserting data using mysqli

This code gets through all of the debugs but for some reason, it is still not inserting. It tries to check if the username already exists in the database and if it doesn't, it adds it. For some reason, it still doesn't add it to the data table. It does get to the insert part but it doesn't add a row.
<?php
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', /*$_POST["username"]*/ $username );
$username = 'hi';
$stmt->execute();
$stmt->store_result();
echo "debug 2";
if ($stmt->num_rows == 0){ // username not taken
echo "debug 3";
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password =(/*$_POST["password"]*/ "hey");
$username =(/* $_POST["username"]*/ "hi");
$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);
$stmt2->execute();
if ($stmt2->affected_rows == 1){
echo 'Insert was successful.';
}else{ echo 'Insert failed.';
var_dump($stmt2);
}
}else{ echo 'That username exists already.';}
?>
You should bind all variables once with bind_param() and not twice or N times. The correct way is pass first the types followed by the variables.
change:
$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);
By
$stmt2->bind_param('ss',$username, $password);
With php5.6 >= you can pass an array with ... operator to simplify.
$data = array('user' => 'someUser', 'password' => 'secret');
$stmt2->bind_param('ss', ...$data);

PDO insert not working correctly

When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>

INSERT INTO SQL php Function does not work

I have managed to write a php script that checks if a username already exists in the database and only adds a new user if it does not already exist.
This is my php script:
<?php
require "init.php";
if(isset($_POST['username']) && isset($_POST['forename']) && isset($_POST['surname']) && isset($_POST['password'])){
$username = $_POST['username'];
$forename = $_POST['forename'];
$username = $_POST['surname'];
$password = $_POST['password'];
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon -> prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($username);
if($result->fetch()){
echo "Can't add new user as it already exists!";
}
else{
$stmt_two = "INSERT INTO users (username, forename, surname, password)
VALUES(?, ?, ?, ?)";
$result_two = $dbcon -> prepare($stmt_two);
$result_two->bind_param('ssss', $username, $forename, $surname, $password);
$result_two->execute();
$result_two->close();
echo json_encode("Success");
}
}
?>
I believe the records are not being inserted or being inserted intermittently due to the fact that I have more than one prepared statement. If I just do the INSERT INTO statement on its' own with the SELECT FROM statement - the records are added almost instantly.
Why is this and what is wrong with my code?
Thanks
Just as I have said in the comments, don't over complicate and just check the number of rows found. No need to fetch anything. You're just checking if that user exists anyway.
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->store_result();
if($result->num_rows() > 0) { // if it exists
} else {
// make your insertions
}
And another note:
isset can take multiple arguments:
if(isset($_POST['username'], $_POST['forename'], $_POST['surname'], $_POST['password'])) {
// and so on
}
Edit: Another flavor (using COUNT() of MySQL):
$stmt = "SELECT COUNT(username) FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($count);
$result->fetch();
if($count > 0) { // exists
} else {
// do something else
}

Registration System PHP, mysqli ( Hashing ) [duplicate]

This question already has answers here:
Where to put password_verify in login script?
(2 answers)
Closed 7 years ago.
Below is a simple registration script using php, I obviously want to store peoples data securely. I was wondering where would be the best place to implement the hashing script? Would it be implemented in the script below or have it alone?
<?php
//values to be inserted in database table
//session_start();
include('connect.php');
$email = $_POST['email'];
$password= $_POST['password'];
$username= $_POST['username'];
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
Another thing, when fetching peoples information from the database so they can sign in do I fetch their hashed password or do I have to recreate a hashed version of the password they've entered? I've read different ways of doing it, I just want to know the most secure. Thank you
EDIT:
This is my login code
<?php
include 'connect.php';
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $mysqli->prepare('SELECT password FROM users WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($password);
$stmt->fetch();
// Account exists, now we verify the password.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
echo 'You have logged in!';
} else {
echo 'Incorrect username and/or password!';
}
} else {
echo 'Incorrect username blar password!';
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
?>
ANSWER:
<?php
//values to be inserted in database table
//session_start();
include('connect.php');
//Fixed cost of 10 to fit server req
//Random salt to be added to the pass
$options = [
'cost' => 10,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
While putting Users value into the variable is the perfect time to sanitize
It would be great if you use a Global function to sanitize data and use that function everywhere
Here is an Example of secure code (without OOP ):
<?php
// create a globa function
//
function string_sanitize($value) {
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
function sanitize($value){
return $this->string_sanitize(htmlentities(trim($value)));
}
//values to be inserted in database table
//session_start();
include('connect.php');
$email = sanitize($_POST['email']);
$username = sanitize($_POST['username']);
// Sanitize password using hash()
$password = hash('sha256', $_POST['password']);
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>

Categories