I've been debugging this small amount of code for hours and cannot solve it. I am trying to find a result inside the database table where the specified username exists.
if (empty($_POST['username'])) {
die("Enter a username please");
} else {
$username = $_POST['username'];
}
// check do username under that name already exists in db ?
function checker()
{
// including username and db variables from global scope
global $db;
global $username;
// making query
$query = "SELECT username FROM game.usersinfo WHERE username = :username";
$select = $db->prepare($query);
$select->execute(['username' => $username]);
return $select;
//expected value of select is false
}
// function call
checker();
The problem is due to PHP PDO->execute() documentation. It will throw an object on success and false on failure. I expect false to show to me, but the object always shows. There is no username in my database table that matches the username that I passed in the parameter. I tried already to use only pdo::query() method, but it didn't work.
Related
I wrote code for sign up where I check username , if it is exists in database or not than add new user accordingly. I am new to sql->prepare statement, Problem is in count function , when checking username it works properly, but in else part when adding user it gives me following error
Uncaught TypeError: count(): Argument #1 ($value) must be of type
Countable|array, bool
Here is my adduser.php code.
<?php
include 'config.php';
//checkusername
$check = $con->prepare("select username from users where username = ?");
$check->bindParam(1,$username);
$username = $_POST['username'];
$check->execute();
$row = $check->fetch(PDO::FETCH_ASSOC);
if(count($row)){
echo -1;
}
else{
$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
$sql->bindParam(1,$name);
$sql->bindParam(2,$username);
$sql->bindParam(3,$password);
$name = $_POST['name'];
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql->execute();
echo 1;
}
?>
It doesn't make much sense to use count here, you don't need to know how many fields are in the row.
Just check if it's false or not - see php.net/manual/en/pdostatement.fetch.php which mentions that fetch() will return false when it fails (i.e. there is no row available).
This would make more sense:
if($row) {
$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
//...etc...
}
else {
echo -1;
}
After executing the query with $check->execute();, you can use the built-in method to count the returned rows: $check->rowCount();.
I think the statement above returned 0 rows, so you can't do $check->fetch() and it returns false.
Example:
// Your code here...
$check = $con->prepare("select username from users where username = ?");
$username = $_POST['username']; // This line needs to be before the next one, because you used the variable $username before defining it
$check->bindParam(1,$username);
$check->execute();
if($check->rowCount() > 0) {
// User does exist
} else {
// User does not exist
}
Edit 2: I just realised that the answer I've given below is wrong. The thing I suggest instead is checking if there's any value by using the PDO rowCount() method, like this: if ($check->rowCount()>0)
wrong stuff below
You're assigining $username a value after binding it.
$check = $con->prepare("select username from users where username = ?");
$check->bindParam(1,$username); //bind $username
$username = $_POST['username']; //assign value
$check->execute();
Try switching those two lines so $username is assigned a value when you're binding it.
$check = $con->prepare("select username from users where username = ?");
$username = $_POST['username']; //assign value
$check->bindParam(1,$username); //bind $username
$check->execute();
Edit
In case you're still having issues, try checking if there's any error in the sql statement execution.
After your $check->execute(); you can add print_r($check->errorInfo()); to see if your MySQL statement has any issues in it.
This question already has answers here:
MySQL password function
(4 answers)
Closed 2 years ago.
I am making a php document the logs the user in if they are in the database and entered the correct username and password. To be secure I am using prepared statements but I can't get the results from my SELECT query to set session variables necessary for my site. Here is my code...
<?php
session_start();
require 'config.php'; #This file has all connection info
#$C is the mysqli connection
#$USERS is the name of the table in my database
$sql = $C->prepare('SELECT ID,Username,Favorites FROM '.$USERS.' WHERE Email=? AND Password=PASSWORD(?)');
$sql->bind_param("ss", $e,$p);
$e = $_POST['e'];#email
$p = $_POST['p'];#password
$query = $sql->execute();
$sql->store_result();
$numrows = $sql->num_rows;
if($numrows == 1) {
$sql->bind_result($id,$username,$favs);
while($sql->fetch()) {
$_SESSION['ID'] = $id;
$_SESSION['Name'] = $username;
$_SESSION['favs'] = $favs;
$_SESSION['valid'] = true;
}
echo 'true';
}
else {
echo 'User Not Found';
}
This just echoes 'User Not Found' because $numrows always = 0 and I made sure that all the entered info was correct.
Move the variable assignments to $e and $p above the call to bind_params or at least declare them above the call.
The parameters to bind_params are passed by reference, so changes to the variables after bind but before execute take effect, but AFAIK the variables have to exist before the bind call.
Working on a log in system, but i keep getting this error
//$User = 'kv96';
//$Pass = 'passkv';
//echo isValidLogin($User, $Pass);
function isValidLogin($username, $password) {
$query = mysqli_query($link,"SELECT * FROM Log_in WHERE Password = '$Pass' AND User_ID ='$User'"); //Finds the database and chooses the row
//$result = mysqli_query($query);
$row = mysqli_fetch_array($result); //Fetches the row
if($row['User_ID'] != null && $row['Password'] != null){return true;}
else{return false;}
function getUsernameRole($username) {
return "instructor";
}
mysqli_close($link);
?>
Can someone explain why this error is popping, i dont see why the query is failing?
I've noticed you commented out your $result yet you were using to fetch the database array. You should be using $query instead, or get rid of the 2 // before your $result.
Not only that, you forgot to parse $link through the parameters of your function. Therefore the query will not be successful.
Another problem, you used $pass and $user variables inside of your query, however, you have not passed them through the parameters of your function either. You must change $username to $user and so on..
I've also changed your while loop to a row count. This will save you from using unnecessary code and is way more practical; saves you doing a while loop and checking if values return null.
function isValidLogin($link, $user, $pass) { // parsing through the connection link and $user, $pass variables
$query = mysqli_query($link,"SELECT * FROM Log_in WHERE Password = '$Pass' AND User_ID ='$User'"); //Finds the database and chooses the row
$count = mysqli_num_rows($query);
if($count > 0){
return true;
} else {
return false;
}
}
A suggestion I would like to make (and HIGHLY recommend) is to use prepared statements to protect against SQL injection, however, you can find many posts on how to do that.
Guys im using Bind_param in php to retrieve Username and password from Login table. my question is how can i fetch all the info of user, and pass it to variable as an object? please see my code below
require 'dbc.php';
require 'security.php';
$myusername=trim($_POST['strusername']);
$mypassword=trim($_POST['strpassword']);
$myusername =escape($myusername);
$mypassword=escape($mypassword);
$sql = "SELECT * FROM login WHERE strusername=? AND strpassword=?";
$stmt = $db->prepare($sql);
$stmt->bind_param('ss',$myusername,$mypassword);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
echo "user verified, Access Granted.";
// while($row=$stmt->fetch_object()){
// $strfullname= $row->strfullname;
// $strcompany= $row->strcompany;
// $strdept= $row->strdept;
// $strloc= $row->strloc;
// $strposition= $row->strposition;
// $strauthorization= $row->strauthorization;
// $stremailadd= $row->stremailadd;
// $strcostcent= $row->strcostcent;
// $strtelephone= $row->strtelephone;
// };
// how to fetch all data in my query using param LIKE THIS
}else
{
echo "Invalid Username or Password";
}
Seems like what you're looking for is extract(), used with fetch_row(). So you'd end up with something like:
while ($row = $stmt->fetch_row()) {
extract($row, EXTR_OVERWRITE);
// your logic here...
}
As fair warning, this will overwrite any variables with the same name as your database columns. Since you're pulling from the database rather than a superglobal you at least know what you're getting into, but it's still a risk, particularly if you've got this code in global scope rather than inside a function/method.
As such, you may want to wrap your row-to-be-extracted in array_intersect_key(), like so:
$allowedFields = array_flip(['strfullname', 'strcompany', 'strdept',
'strloc', 'strposition', 'strauthorization', 'stremailadd',
'strcostcent', 'strtelephone']);
while ($row = $stmt->fetch_row()) {
extract(array_intersect_key($row, $allowedFields), EXTR_OVERWRITE);
// your logic here...
}
so your code documents which fields will suddenly turn into (local or global) variables.
I have a forum page and want a simple login for user with usernames from a predefined mysql user table. I use a login.php form file link from the forum, a get $_POST username, then use a login_handle.php file that calls a function to connect to the DB, query the users array, and try to validate that the $_POST username is in the queried list array.
The function is below, and then the call in login_handle.php I'm getting various errors and don't know if this is at all a good approach. I also want to start a session during the form and verification that can grab the $_POST username as a $_SESSION username and apply to subsequent forum pages.
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users";
$result = mysql_query($query);
$usernames = mysql_fetch_assoc($result);
$isUname = true;
if(!in_array("username", $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
------------------handler call-----------
$username = $_POST["username"];
$password = $_POST["password"];
if(isUsername($username)==true){ // Check if username is valid.
//$Uname = $_SESSION['username'];
//echo "Username = " . $Uname;
echo 'go to forum';
}
First, mysql is deprecated. Please use mysqli.
Second, why don't you use something like...
function isUsername($username){
$query = "SELECT username FROM users WHERE username == '" . $username . "'";
Third: did you search and research?
These kind of question can be easily find everywhere.
As simple as it is , you need to query the specific username from $_POST , not the whole usertable.
I think requesting the number of rows ( number of apparition is a good way to get if user is in database or not , you can make it greater (>=) instead of one user condition (==)).
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users where username='$username'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
$isUname = true;
if($rows==1) {
$isUname = true;
}else{
echo "Please enter valid user name.<br>";
$isUname = false;
}
return $isUname;
}
I used nearly the same function when I manually assigned a txt array to a variable $username to compare. Now that I am using a user table I merely want to assign the an array of the queried users (thought mysql_fetch_assoc($result) creates the same type of assoc. array) to $username instead of the hard copied elements where it worked with before. Is the array produced with the query different than the $usernames=array("jes34","pes22","jis44","jll124"); that prevents me from doing this?
function isUsername($username){ //Test if proper Username from array.
$usernames=array("jes34","pes22","jis44","jll124");
$isUname = true;
if(!in_array($_POST["username"], $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
-----function call---
if(isUsername($username)==true){ do something }