I have this MYSQL Table :
id | action
A6bIMWP1rQ changedusername
A6bIMWP1rQ changedusername
Now how i make this php function to count if more then 5 times changedusername exsit, it will return false?
i have tryed:
function checkIfOverFive($id,$mysqli) {
global $func; //The database connection
if ($stmt = $mysqli->prepare("SELECT action FROM userchange_attemps WHERE user_id = ?")) {
$stmt->bind_param('i', $id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there has been more than 5 failed logins
if($stmt->num_rows > 5) {
return true;
}else{
return false;
}
}
}
And how with php i determine how much left attemps upto 5 ?
Lets say now in my table theres 2 rows, and left 3 , how i return that value to the user ?
Thanks.
Use mysql COUNT
function checkIfOverFive($id,$mysqli) {
global $func; //The database connection
if ($stmt = $mysqli->prepare("SELECT COUNT(id) as count FROM userchange_attemps WHERE user_id = ? AND action = 'changedusername'")) {
$stmt->bind_param('i', $id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
$row = $stmt->fetch_assoc();
if($row['count'] > 5) {
//do something
} else {
//do something else
}
}
}
How about...
SELECT COUNT(action)
FROM userchange_attemps
WHERE action = 'changedusername' AND user_id= ?
Related
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 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.
I'm trying to figure out why a mysqli parepared statement is not working. I can say the page have something like 2 sections, the first one needs $_GET to be empty and the last one needs $_GET['id'] and other to be set (isset). Both "sections" have the same query but in the last section there's a different query first.
Everyting is working fine until the repeated query in the last "section", where nothing is printed.
I have something like this:
if (login_check($mysqli) == true) {
if(empty($_GET)) { //first section
if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.* FROM friends INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.userID = ? AND members.acc_type = ?")) {
$stmt->bind_param('is', $_SESSION['user_id'], $_SESSION['acc_type']);
$stmt->execute();
} else echo $mysqli->error;
$result = $stmt->get_result();
// php/mysqli stuff working as expected ($row[] printing db data)
// no need to close
}
if(isset($_GET['id'], $_SESSION['user_id'])) { // last section
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT COUNT(*) rowCount FROM friends WHERE friendID = ? AND userID = ?")) {
$stmt->bind_param('ii', $_GET['id'], $_SESSION['user_id']);
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($rowCount);
/* fetch values */
if($stmt->fetch()) {
if ($rowCount > 0) { // This check is working fine, I tested.
$stmt->close(); // close here so no "non-object" error
$stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.* FROM friends INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.friendID = ? AND members.acc_type = ?");
$stmt->bind_param('is', $_GET['id'], $_SESSION['acc_type']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
// Here I have some $row['columns'] and nothing is printed.
} else{
echo $_SESSION['username'], ', you are not allowed to be here.';
}
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
}
} else {
echo 'Please, log in.';
}
The first query is working fine, the other is a copy/paste.
I don't see where the problem is :(
Thanks!
Edit: sorry the second query should be "WHERE friends.friendID".
for ($i = 1; $i < 13; $i++) {
$month = $row['month' . $i];
if($row[$month] == 1) {
$paid[] = 'Paid';
} else {
$paid[] = 'Not Paid';
}
$bonus = $row['bonus'];
}
The problem is members.monthx and friends.monthx have the same name, but they are not meant to have the same values so I don't know from what table is getting $row['month' . $i]. The value should be taken from friends.monthx. How do I specify that?
I am having some trouble with prepared statements. Basically, this query is returning no rows, even though I know for a fact that this query should return multiple rows. I thought this was just a problem due to SQL injections, but maybe I'm doing something else wrong here, I don't know. If I take out the check for how many rows there are, I get an error:
PHP Fatal error: Call to a member function fetch_array()
Any help would be appreciated!
$stmt = $mysqli->prepare("SELECT sid from SDS WHERE uid=? AND dst=?");
$stmt->bind_param('ss',$username,$structureType);
$stmt->execute();
$stmt->bind_result($results);
$stmt->fetch();
if ($results) {
if($results->num_rows == 0) {
print("No results here.");
return 0;
}
$recordnames = array();
while ($next_row = $results->fetch_array()) {
$recordnames[] = $next_row['sid'];
}
return $recordnames;
}
When you use $stmt->bind_result($result); you are binding the sid from the database to the variable $results. So you cannot perform operations like :
if($results->num_rows == 0) { //... }
or
$results->fetch_array();
This is how I would do it :
<?php
$stmt = $mysqli->prepare("SELECT sid from SDS WHERE uid=? AND dst=?");
$stmt->bind_param('ss', $username, $structureType);
$stmt->execute();
$stmt->bind_result($sid);
$stmt->store_result();
if ($stmt->num_rows == 0)
{
print("No results here.");
$stmt->close();
return 0;
}
else
{
$recordnames = array();
while($stmt->fetch())
{
$recordnames[] = $sid;
}
return $recordnames;
}
?>
This way uses a different logic, check if the row count is 0, if so display "No results here", if not put results into the array.
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.