I am getting very frustrated. I have two functions which have similar "instructions" ie: return values from a users table in the database.
The second one works fine, however the first one is returning an empty value.
Here is the code:
public function ValidateUser($username, $password)
{
$stmt = "SELECT password FROM users WHERE username = :username LIMIT 1";
if(!($grabUser = $this->db->prepare($stmt)))
{
return null;
}
$grabUser->bindParam(":username", $username, PDO::PARAM_STR);
$grabUser->execute();
$data = $grabUser->fetch();
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
echo $data['password'].'s';
if(!password_verify($password,$data['password']))
{
return null;
}
return $this->core->encrypt($data['password']);
}
I'm trying to display the $data['password'] on the page just to test whether it returns a value from the database, however it is simply returning empty, whereas the query is returning a column because it passes the
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
condition.
The $username and $password variables are both set, so they are no problem.
Just in case you ask, this is the function that does work properly:
public function ValidateFacebookUser($email, $fid)
{
$stmt = "SELECT username, password FROM users WHERE email_address = :email AND connected_fb = '1' AND connected_fb_id = :fb LIMIT 1";
if(!($grabUser = $this->db->prepare($stmt)))
{
return null;
}
$grabUser->bindParam(":email", $email, PDO::PARAM_STR);
$grabUser->bindParam(":fb", $fid, PDO::PARAM_INT);
$grabUser->execute();
$data = $grabUser->fetch();
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
return array($data['username'], $this->core->encrypt($data['password']));
}
It does turn the username and password for that case. Why does it not work in the first function?
Thanks.
No, you shouldn't mix up ->fetchColumn and ->fetch and with LIMIT 1.
What happens is that you already ->fetch() the first row. After that invocation of ->fetchColumn(), there's no more row to fetch.
public function ValidateUser($username, $password)
{
$stmt = "SELECT password FROM users WHERE username = :username LIMIT 1";
if(!($grabUser = $this->db->prepare($stmt))) {
return null;
}
$grabUser->bindParam(":username", $username, PDO::PARAM_STR);
$grabUser->execute();
$data = $grabUser->fetch(); // fetch once
// no need to add ->fetchColumn checking
$ret = null;
if(!empty($data['password']) && password_verify($password,$data['password'])) {
$ret = $this->core->encrypt($data['password']);
}
return $ret;
}
Look at the manual for fetchColumn(). You can see that this fetches the next result set. So if you've already called fetch(), there should be no next result set as per your code:
$data = $grabUser->fetch();
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
This will always return null with a LIMIT 1 or single row result.
Related
I have a simple problem whitch I can't solve, because I am starting with OOP and in the same time with MySQLi.
I need these function universal for everything and I need SET statement dynamically changed.
This is my update function these not working
public function updateUser($user, $pass, $dbSet) {
if($this->getUser($user, $pass) != NULL) {
$sql = $this->connection->prepare("UPDATE users SET ? WHERE user = ?");
$sql->bind_param('ss', $dbSet, $user);
$sql->execute();
$sql->close();
return true;
} else {
return false;
}
}
Variable $dbSet contains different values. For example:
$dbSet = "last_activity = ".$last_activity;
Or complex
$dbSet = "name = ".$newName.", surname = ".$newSurname.", email = ".$newEmail;
But when I change it for one SET statement, it works...
...
$sql = $this->connection->prepare("UPDATE users SET last_activity = ? WHERE user = ?");
...
please i have an issue with codeigniter. when i try to log here is the result:
Fatal error: Call to a member function num_rows() on boolean in D:\xampp\htdocs\procurementSys\application\models\login_model.php on line 19
Below tho code of the relative file:
<?php
class Login_model extends CI_Model {
//this function checks whether the username and the password is in the database or not
public function check_login($username, $password){
$this->db->select('username, password, status');
$array = array('username' => $username, 'password' => sha1($password),'status' => 'active');
$this->db->where($array);
$query = $this->db->get('user');
if($query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
}
//this function returns the status of the user to be used in authentication
public function user_login_data($username, $password){
$this->db->select('status');
$array = array('username' => $username, 'password' => sha1($password));
$this->db->where($array);
$query = $this->db->get('user');
if($query->num_rows() == 1) // if the affected number of rows is one
{
$row = $query->row();
return $row->status;
}
// else
// {
// return false;
// }
}
public function user_role($username){ // this function gets the user's role from the database
$this->db->select('role');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0);
return $row->role;
}
public function department($username){ // this function gets the user's department from the database
$this->db->select('department');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0); // returns the first row with an array of objects that is stored in the row variable
return $row->department;
}
public function get_user_id($username){ // this function gets the user's department from the database
$this->db->select('userID');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0); // returns the first row with an array of objects that is stored in the row variable
return $row->userID ;
}
public function fullname($username){
$this->db->select('firstName, secondName');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0);
return $row;
// foreach($query->result() as $row) // returns the query as an array of objects
// {
// $data[] = $row; // equates the array of objects to an array variable
// }
//
// return $data;
// }
}
}
?>
I kept searching for a solution and found this post (Call to a member function num_rows() on boolean) . It gave me an idea but no real help. thanks
I got this error with MySQL Strict Mode enabled. When I disable Strict Mode, error disappeared.
To check this mode is already enabled
SHOW VARIABLES LIKE 'sql_mode';
To make it disabled
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
Something like this for the count:
$this->db->select('id');
$this->db->from('table');
$this->db->where($your_conditions);
$num_results = $this->db->count_all_results();
**Try something like this **
//this function checks whether the username and the password is in the database or not
public function check_login($username, $password){
$this->db->select('username, password, status');
$array = array('username' => $username, 'password' => sha1($password),'status' => 'active');
$this->db->where($array);
$query = $this->db->get('user');
$result = $query->result();
if($result->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
}
CODEIGNITER send boolean as result if there is not result
for example as per your method
public function check_login($username, $password){
$this->db->select('username, password, status');
$array = array('username' => $username, 'password' => sha1($password),'status' => 'active');
$this->db->where($array);
$query = $this->db->get('user');
if($query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
If there is no data in table it send False while we are expecting some object on which we can work so before calling $query->num_rows() check if it is an object or not so code can be like :
$query = $this->db->get('user');
if(is_object($query)){
if($query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
}else{
return false;
}
You can write like that. It will work smoothly.
if($query !== FALSE && $query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
The function should return the id of the found user or return false if not found.
Currently I am using bind result and fetch to check if a user is found in an mysql table:
public function getUserIDByName($UserName) {
$uid = "";
$i=0;
if($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")){
$stmt->bind_param("s", $UserName);
$stmt->execute();
$stmt->bind_result($uid);
while($stmt->fetch()){
$i++;
}
$stmt->close();
}
if($i==0){
return false;
}else{
return $uid;
}
}
This works, but I assume that there is a proper way to do this without a counter in the fetch loop. I can not use get_result as mysqlnd is not available.
Simple use num_rows to check your query return result or not
function getUserIDByName($UserName) {
if ($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")) {
$stmt->bind_param("s", $UserName);
$stmt->execute();
$row_cnt = $stmt->num_rows;
if ($row_cnt == 1) {
$stmt->bind_result($uid);
while ($stmt->fetch()) {
return $uid;
}
} else {
return false;
}
}
}
Use this instead
public function getUserIDByName($UserName)
{
$uid = '';
$response = false;
$stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?");
$stmt->bind_param("s", $UserName);
$stmt->execute();
$stmt->bind_result($uid);
if ($stmt->fetch()) {
$response = $uid;
}
$stmt->close();
return $response;
}
EDIT: just realized you're using mysqli and not pdo. Ill leave this here if you want to use PDO in the feature I guess.
This is how I would do it. You could change rowcount() > 0 to rowcount() === 1 if you want to guarantee only 1 user is found.
public function getUserIDByName($UserName)
{
$stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name = :name");
// bind :name to the username
$stmt->bindParam(":name", $UserName);
// execute the query
$stmt->execute();
// check the rowcount
if ($stmt->rowcount() > 0) {
// fetch the results as a associative array
return $stmt->fetch(PDO::FETCH_ASSOC);
}
// return false because rowcount wasn't bigger than 0
return false;
}
I'm newbie in PHP and WordPress. This approach was working fine for me in ASP.NET but here both queries are not working. When I comment the first one, the second one(Insertion) is working fine.
$dbhostname="111.1.11.111";
$dbusername="db_userName";
$dbpassword="mypassword";
$con=mysqli_connect($dbhostname,$dbusername,$dbpassword,"db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Check wether the email exists or not ?
$sql="CALL Select_ConfirmEmailExistance('abc#abc.com')";
$containsResult=0;
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_assoc($result))
{
if (isset($fieldinfo)) {
$containsResult=1;// Email Exists
}
}
mysqli_free_result($result);
if ($containsResult==0) { // In case email does not exists enter it.
$sql="CALL insert_Userinfo('abc','def','abc#abc.com','mnop')";
if ($result=mysqli_query($con,$sql))
{
$data;
while ($fieldinfo=mysqli_fetch_assoc($result))
{
$data[]=$fieldinfo;
}
}
}
print_r($data);
}
mysqli_close($con);
First Store Procdure
BEGIN
SELECT 1 as emailstatus FROM userinfo WHERE email= p_email;
END
Second Stored Procedure
INSERT INTO `userinfo` (
`first_name`,
`last_name`,
`email`,
`password`
)
VALUES
(
`FName`,
`LName`,
`Email`,
`Pass`
);
SELECT
user_id
FROM
userinfo
ORDER BY
user_id DESC
LIMIT 1;
Here is what I was talking about when I said create a query class to fetch data. This is just a simple one, but it works pretty effectively and you can build it out to be pretty powerful.
class DBEngine
{
public $con;
public function __construct($host="111.1.11.111",$db = "dbname",$user="db_userName",$pass="mypassword")
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($rows = $query->fetch(PDO::FETCH_ASSOC)) {
$array[] = $rows;
}
}
return (isset($array) && $array !== 0 && !empty($array))? $array: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Create an instance of the engine
$query = new DBEngine();
// Query 1 will return an array or false (0)
$call1 = $query->Fetch("CALL Select_ConfirmEmailExistance('abc#abc.com')");
// Assign your true/false
$containsResult = ($call1 !== 0)? 1:0;
// Run second query and return array or false (0)
if($containsResult == 0)
$data = $query->Fetch("CALL insert_Userinfo('abc','def','abc#abc.com','mnop')");
// Display returned result
print_r($data);
It is quite simple. Your code is fine but you only have to create two separete functions and simply call those functions instead of the code directly.
I am trying to match a username in the database. If the username match it returns true otherwise it returns false.
At the moment it will always return false even when the username is correct.
Here is the class and call I'm using:
class register{
private $result;
public function __construct($post_data, PDO $dbh){
$this->post_data = array_map('trim', $post_data);
$this->dbh = $dbh;
}
public function checkUsername(){
$stmt = $this->dbh->prepare("COUNT(*) FROM oopforum_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['reg_username'], PDO::PARAM_STR);
$stmt->execute();
$this->result = $stmt->rowCount();
if($this->result == 0){
return false;
}else{
return true;
}
}
}
$register = new register($_POST, $dbh);
if($register->checkUsername()){
//continue
}else{
echo 'ERROR: That username is taken, please choose another one.';
}
Why is it returning false even though the username's do match?
You forgot the SELECT statement:
$stmt = $this->dbh->prepare("SELECT COUNT(*) FROM oopforum_users WHERE username = ?");
Apart from that your query will always return a row (exactly 1 row), but the contents of that row could contain a 0 for the row count, so you need to change your logic: Either select a real column instead of COUNT(*) and use $stmt->rowCount() or read the value of the count and check for that.