how can i get the value of COUNT(id) - php

I'm encountering a problem with this object. I don't know (if it is possible), how to get the value of COUNT(id).
I tried $req[0]->COUNT(id) but "COUNT()" it detected it as a function. How could it be detect as a key?
Here's a var_dump($req):
object(stdClass)[4]
public 'COUNT(id)' => string '1' (length=1)
PHP
$req = $db->query('SELECT COUNT(id) FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');
if($req == 1){
$_SESSION['authentificated'] = true;
$_SESSION['username'] = $username;
}
var_dump($req);
The output of the query should be 0 or 1 if the user is already register or not.

1.You need to add alias for COUNT()
2.After query execution you need to fetch record and then do the comparison
Do like below:-
$req = $db->query('SELECT COUNT(id) as count FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');
$result = mysqli_fetch_assoc($req); // sample example,you need to change accordingly
if($result['count'] == 1){
//your code
}
Note:-
Saving plain password is very bad idea. so use password hashing
Your current code is wide-open for SQL INJECTION. To prevent from it use prepared statements
mysqli::prepare
PDO::prepare
I will do it something like this: https://3v4l.org/YOBGX

Here alias required or else it won't capture that count value the way you want.
$req = $db->query('SELECT COUNT(id) cnt FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');
var_dump($req);

Here is the solution you have not bind the key for that please see below
$req = $db->query('SELECT COUNT(id) as user_exists FROM `users` WHERE username
="'.$username.'" AND password = "'.$password.'"');
if($req == 1){
$_SESSION['authentificated'] = true;
$_SESSION['username'] = $username;
}
var_dump($req);

Try this --
$req = mysqli_query($db,'SELECT (COUNT(id)) as countID FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"'));
$row = mysqli_fetch_array($req);
$countID = $row['countID'];
if($countID == 1){
$_SESSION['authentificated'] = true;
$_SESSION['username'] = $username;
}
var_dump($req);

Related

PHP, SQL update single colum ( password )

I need help with update my column in database. I use InnoDB, probably problem is here
$sql_update_heslo = "UPDATE users SET u_password = $_noveHeslo WHERE u_name = '$_SESSION[username]'";
first I am checking if Button was clicke. If yes, then I am checking if there is only 1 user with this name who is logged in, then I am checking if MD5 password from the database is same as user input, if yes then update password based on the user entry.
if (isset($_POST['pass_aktualizovat'])) {
$_old_password = md5($_POST['o_pass']);
$sql_search_for_all_userss = "SELECT * FROM users WHERE u_name = '$_SESSION[username]' ";
$result = mysqli_query($connect_to_db, $sql_search_for_all_userss);
// ak sa najde jedna zhoda v databazy
if ($db_data = mysqli_num_rows($result) == 1) {
while (mysqli_fetch_assoc($result)) {
$_aktualneHeslo = $db_data['u_password'];
}
if (md5($_POST['o_pass'])==$_aktualneHeslo) {
$_noveHeslo = md5($_POST['n_pass']);
$sql_update_heslo = "UPDATE users SET u_password = '$_noveHeslo' WHERE u_name = '".$_SESSION['username']."'";
mysqli_query($connect_to_db, $sql_update_heslo);
echo "treti";
}
echo "druhy";
}
echo "prvy";
}
?>

I can't figure out how to update my last inlog time

I'm trying to make an last activity function for an website. but i can't get it to work. I hope you guys can help me out here.
this is my query:
$last_activity_query = "UPDATE users_table SET user_name = '$user_name' WHERE 'date_last_inlog' = NOW()";
$result_update = mysql_query($last_activity_query);
$last_activity_update = mysql_fetch_array($result_update);
this is an print screen of my database table:
I want to store this update in the last row.
Thanks in advance!
i've changed my script now but its still not changing anything in my database table.
this is the change:
if (isset($_REQUEST['inlog_submit'])){//checks if form is submitted
$user_name = $_REQUEST['username_input'];//request username from inlog_form
$password = $crypt;//gets enqrypted pass
//$tbl_name="user_table"; // Table name
$query = "SELECT * FROM users_table WHERE user_name= '$user_name' AND password='$password'";//query stored in var
$last_activity_query = "UPDATE users_table SET 'date_last_inlog' = NOW() WHERE user_name = '$user_name'";
$result = mysql_query($query);//var with result of query
$result_update = mysql_query($last_activity_query);
if ($user_name = mysql_fetch_array($result)){//checks inlog data from form with the $result query
$_SESSION['user_name'] = $user_name[user_name];//creates session with username
$_SESSION['password'] = $password[password];//creates session with password
$last_activity_update = mysql_fetch_array($result_update);
header ('Location: admin.php');//when login is correct redirect to specified page
}else{
$error_inlog = 10;//when inlog data is incorrect this error will show
}
}
?>
Your SQL query is in the wrong order.
$last_activity_query = "UPDATE users_table SET 'date_last_inlog' = NOW() WHERE user_name = '$user_name'";
Your logic is incorrect. Use this:-
"UPDATE users_table SET 'date_last_inlog' = NOW() WHERE user_name = '$user_name'";
You are using this :-
UPDATE users_table SET user_name = '$user_name' WHERE 'date_last_inlog' = NOW()
You are trying to update user_name column where the date_last_inlog column value is equal to the current time which is logically incorrect.

Boolean given where parameter should be resource

I'm having one error when I try to use my function and I don't know how can I fix it.
function is_valid($email_e, $email_code_e, $username_e) {
$email = mysql_real_escape_string($email_e);
$email_code = mysql_real_escape_string($email_code_e);
$username = sanitize($username_e);
return (mysql_result
(mysql_query
("SELECT COUNT(*) FROM `users`
WHERE `username` = $username
AND `email_code` = $email_code
AND `email` = $email"), 0) == 1) ? true : false;
}
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /home/meuts3/public_html/core/functions/users.php on line 34
I'm trying to make a forget password system and when someone try to get a new password, he receives a link with email_code, username and email. When he clicks, he goes to a changepassword page, in this page, I will check if these information is valid using the function is_valid, so if is_valid I have to return the user_id to start a session user_id.
How can I do that?
Thanks, I really appreciate you guys.
You have an error in sql statement. You must quote $username, $email_code & $email in ''.
SELECT COUNT(*) FROM `users` WHERE `username` = '$username' AND `email_code` = '$email_code' AND `email` = '$email'
So mysql_query returns false, not a resource object.
Try this:
function is_valid($email_e,$email_code_e,$username_e) {
$email = mysql_real_escape_string($email_e);
$email_code = mysql_real_escape_string($email_code_e);
$username = sanitize($username_e);
$sql = "SELECT user_id FROM `users`
WHERE `username` = $username
AND `email_code` = $email_code
AND `email` = $email";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) <= 0)
return -1;
return mysql_result($result,1);
}
first, avoid mysql_* functions as they're deprecated.
second,
the process should be like,
we select the user_id
If number of rows fetched is 0 then no such user else we get a unique user_id
so let's write the sql considering your column name for user_id is user_id and user_id is always>0:
$q = "SELECT user_id FROM `users` WHERE `username` = '$username' AND `email_code` = '$email_code' AND `email` = '$email'";
$r = mysql_query($q); //warning I don't like mysql_* functions
if(mysql_num_rows($r)>0){ //we have got more than 0 rows
$d = mysql_fetch_assoc($r);
return $d['user_id'];
} else { // No such username, email, email_code combination found in database
return 0;
}

Generate a simple array of username using PDO

My Database
id username
1 xxx
2 bbb
3 vvv
4 bbbbbb
i need output as
array('xxx','bbb','vvv','bbbbb');
Using PDO i need to fetch username from db & make that to array, is to for checking username exists
If you're only checking if a username exist, it would be optimal to modify your query to do just that, instead of returning excess data:
$query = $pdo->prepare("SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1");
$query->execute(array($username_to_test));
if ($query->rowCount() == 1)
{
// user exists in table
}
If you do happen to need an array of usernames, do something like the following:
$usernames = array();
$query = $pdo->query("SELECT `username` FROM `users`");
while(($row = $query->fetchObject()) != null)
$usernames[] = $row->username;
$pdo = new PDO($dsn,$user,$pass);
$pdos = $pdo->prepare('select username from mytablename');
$pdos ->execute();
$results = array();
while ($row = $pdos->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row['username'];
}
var_dump($results);
Set Your database $dsn, $user and $pass before according to doc.
To do exactly what you've asked:
$query = $dbh -> prepare("SELECT username from users");
if ($query -> execute()){
$user_array = $query -> fetch(PDO::FETCH_ASSOC);
}
Tim Cooper's answer is probably a better solution though.

hash passwords not matching

I'm using the functions below. When I register a user, the hash seems to work fine. When I try to login the hash doesn't match. It has the correct hash, plus extra hash.
What's the issue?
function salt($pass){
$salt = 'hello';
return hash('sha512', $pass.$salt);
}
function valid_credentials($user,$pass) {
$user = mysql_real_escape_string($user);
$pass = salt($pass);
$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '".$user."' AND `password` = '{$pass}' ");
return (mysql_result($total, 0) == '1' ) ? true : false;
}
function add_user($user, $pass) {
$user = mysql_real_escape_string(htmlentities($user));
$pass = salt($pass);
$time = now();
mysql_query("INSERT INTO `users` ( user_name, password, date_created ) VALUES ( '{$user}', '{$pass}', '{$time}' )");
}
I think in your validation code this line:
$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '".$user."' AND `password` = '{$pass}' ");
needs to be changed to something like so:
$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '".$user."' AND `password` = '".$pass."' ");
Right now it appears to be checking for the password column being equal to "{$pass}".
just double check your value returned before and after inserting the value to db table. Echo it with a trim function. or use strcmp to check the values that is inserted in the db with your generated value.

Categories