why my MySQL queries executed before PHP Conditional check? - php

I'm learning to create conditional event where sql checkout data where is exists before inserting data so they don't conflicted.
i've tried using mysql row check in php then check if query empty before i tried to validate the query executed properly.
also trying to close db connection when conditional satisfied but it worthless anyway.
$user = addslashes(strtolower($usr));
$mail = addslashes(strtolower($mail));
$pass = md5(addslashes($pwd));
$check = $db->query("SELECT EXISTS(SELECT *
FROM `users`
WHERE LOWER(`username`) = LOWER('$user')
OR LOWER(`email`) = LOWER('$mail'))");
if (!$check) {
$db->close();
return false;
} else {
$sql = "INSERT IGNORE INTO `users` (`username`, `password`, `email`)
VALUES ('$user', '$pass', '$mail')";
$query = $db->query($sql);
$db->close();
return true;
}
I'm expecting it execute my queries while data was empty and return false while data has been existed.

Your main issue is that $check will always be a truthy value, so long as the query never fails. If the query returns 0 rows, it is still a true object.
You should instead check if there were any values returned. You can also simplify the query quite a bit, given that MySQL is case-insensitive, and you don't need to check if the result exists. Using a prepared statement, the code would look like this
$stmt = $db->prepare("SELECT username FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $usr, $mail);
$stmt->execute();
$check = $stmt->fetch();
$stmt->close();
// True if the user exists
if ($check) {
return false;
} else {
$stmt = $db->prepare(" INSERT INTO users (username, password, email) VALUES (?, ?, LOWER(?))");
$stmt->bind_param("sss", $usr, $pass, $mail);
$stmt->execute();
$stmt->close();
}
That said, you should not use md5() for passwords - use password_hash() with password_verify() instead.

you can change your code like this
$check = $db->query("SELECT EXISTS(SELECT * FROM `users`
WHERE LOWER(`username`) = LOWER('$user')
OR LOWER(`email`) = LOWER('$mail'))");
$check = $conn->query($sql);
$value = $check->fetch_row()[0];
if($value > 0 ){
echo "existed".$value; // you can change accordingly
}else{
echo "doesn't exist"; // this also
}
Because database respond the query in 1 for exist and 0 for non-exist so the num_row will be always 1 thats why we cant determine the existence with num_row so we have to fetch the value.

Related

MySQLi Prepared statement query won't run

I was trying to make an API of post method that and take one value from the database from my post method.
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$response = array();
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$key_check = $_POST['key_check'];
require_once('Connection.php');
$check_key = "SELECT key_check FROM testing1 WHERE username =? AND password =?";
$insert_key= "UPDATE testing1 SET key_check =? WHERE username =? AND password = ?";
// $insert_key = "INSERT INTO MyGuests (username, password, key_check) VALUES (?, ?, ?)"
if ($result_p = mysqli_prepare($connection,$check_key)){
mysqli_stmt_bind_param($result_p,"ss",$username,$password);
mysqli_stmt_execute($result_p);
$row = $result_p ->get_result();
while ($row1 = $row -> fetch_assoc()){
if(isset($row1["key_check"])){
if($result_p2 = mysqli_prepare($connection,$insert_key)){
mysqli_stmt_bind_param($result_p2,"sss",$username,$password,$key_check);
mysqli_stmt_execute($result_p2);
mysqli_stmt_close($result_p2);
}
}else{
//do something
}
}
}
else{
//do something
}'''
As you can see in the code above, The code will take the key_check value from the first query and then then based on the result if it's null or not, the program will run the second query to add the data from the from the post method. I already checked that the value is null but for some reason the second query did not want to run, is there any thing that I could do or does my logic is wrong in the first place?

SQL Query username:password

Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)
If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();
I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);
You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.
$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)

testing for existance of a row in a table using mysqli prepared statement

Ive written the following method to test whether a user with username $uname exists in a mysql database. unfortunately it returns no rows, even in cases where the user definately exists. im presuming there is a complication because its a prepared statement but im not sure how/
public function isUserExists($uname)
{
$b = false;
$sql = "SELECT * FROM `User` WHERE `username` = ?";
$stmt = $this->conn->prepare($sql);
$stmt->bind_param('s',$uname);
$result = $stmt->execute();
echo "num rows: ".$stmt->num_rows;
if($stmt->num_rows >= 1)
{
echo "user already exists"."<br />";
$b = true;
}
return $b;
}
You have to retrieve the result after executing the query in order to work with the results. Add $stmt->store_result(); after the execute but before you use num_rows.

how to check the result of the mysql query in php

I have a html form for the user to login to the website but i want to check if the following query retun true or false, I am using the PDO so I cant use the method mysql_num_rows();
<?php
$view = new stdClass();
$view->login = 'Homepage';
if(isset($_POST['firstName']) && isset($_POST['password']) )
{
$_firstName = $_POST['firstName'];
$password= $_POST['password'];
$user = new UserPassword(); $user->getLogin($_firstName, $passWord);
}
require_once('Views/login.phtml');
public function getLogin($userName,$passWord) {
$sqlQuerys = "SELECT `id`, `username`, `password`, `firstname`, `surename` FROM `sta177users` WHERE username = ' $userName' AND password = '$password'";
echo $sqlQuerys;
$statement = $this->_dbHandle->prepare($sqlQuerys);
$statement->execute();
}
}
You are not actually executing any query. You are setting a variable, but not executing the code.
Also, by building SQL statements with outside variables, you are leaving yourself open to SQL injection attacks. Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. My site http://bobby-tables.com/php has examples to get you started, and this question has many examples in detail.
You execute the query and you fetch a row. If the result of that fetch is not empty, you have a valid user.
Very important: You need to salt and hash your passwords and use prepared statements to avoid sql injection.
try this solution
$query="SELECT `id`, `username`, `password`, `firstname`, `surename` FROM `sta177users` WHERE username = ' $_firstName' AND password = '$password'";
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
You wanna do something like this:
function emptyQuery($db) // assume $db is your PDO object
{
// your prepared sql statement with PDO::prepare()
$sql = $db->prepare("SELECT `id`,
`username`,
`password`,
`firstname`,
`surename`
FROM
`sta177users`
WHERE
username = ' $_firstName'
AND password = '$password'
");
// execute it with PDO::execute()
$sql->execute();
// return all the rows with PDO::fetchAll(), and then see if the array is empty().
return empty($sql->fetchAll());
}
?>
This should implement your specification. You can use count() for a count, etc.
Of course, do not forsake the documentation:
http://us2.php.net/pdo
Hope that helps!

PHP/MYSQL Retrieve Name based on another criterion

So I have a login system and I want to retrieve the first name of the person who is logged in. Here's my php:
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT `First Name`, Username, Password
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// User exist
return true;
$stmt->close();
}
else {
// User doesn't exist
return false;
$stmt->close();
}
}
this is part of a class who has 1 private variable $conn. The login works perfectly but i just want to get the person's first name. How do I do that?
First off, NEVER grab the password from the database, that is just extremely bad practice.
Second, you only want to accept the user as correct if ONLY one row is returned.
lastly bindColumn is what you're looking for.
<?php
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT `First Name`, Username
FROM table
WHERE Username = :un AND Password = :pwd";
// Don't limit the query to only one, if there is a chance that you can
// return multiple rows, either your code is incorrect, bad data in the database, etc...
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
// Only assume proper information if you ONLY return 1 row.
// Something is wrong if you return more than one row...
if ($stmt->rowCount() == 1) {
// User exist
$stmt->bindColumn('First Name', $firstName);
$stmt->bindColumn('Username', $username);
// You can now refer to the firstName and username variables.
return true;
$stmt->close();
} else {
// User doesn't exist
return false;
$stmt->close();
}
}
?>
That should work for you.
just change the query statement?
$query = "SELECT `First Name`
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";
if that throws errors, you would have to show more of what the class is doing to manage the db transaction
just change this line, to select only First Name in the query:
$query = "SELECT `First Name`, Username, Password
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";`
to
$query = "SELECT `First Name`
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";`
You need to bind the result as below
if ($stmt->rowCount() > 0) {
$stmt->bind_result($fname, $uname, $pwd);
$stmt->fetch()
echo $fname // here you get firsname
// either you can return this $fname or store into session variable for further
// User exist
return true;
$stmt->close();
}
else {
// User doesn't exist
return false;
$stmt->close();
}
In the section where you are returning true you could instead return the actual user data (and array with data will evaluate to true anyway).
Word of warning, you should use hashed passwords. Do not store the password y plain.

Categories