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
}
Related
Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();
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);
How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.
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!";
}
I am trying to get variables from query and store them as cookies using this Query:
$query="SELECT id,username,password FROM employee where email='$email' AND password='$password' Limit 1";
$result= $mysqli->query($query);
if($result->num_rows == 1){
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password);
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['user_id'] = $user_id;
//used echo to check stored variables
echo "user_id=".$_SESSION['user_id'];
//used echo here to check the query result
$_SESSION['username'] = $username;
echo "username=".$username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
}
else{
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
What I see in website is that:
user_id=0username=
Thats how i solved my problem:
$quer="SELECT id,username FROM employee where email=?";
if($result->num_rows == 1){
$stmt = $mysqli->prepare($quer);
$stmt->bind_param('i',$email);
$stmt->execute();
$stmt->bind_result($user_id,$username);
Added:
while($stmt->fetch()) {}
For:
echo "Cookies username:".$_SESSION['username']." ";
echo "db username".$username;
Got result:
Cookies username:test_user db usernametest_user
Thanks for the help guys.