I'm working on something a bit more for myself, thats for another website that I own. It involves a lot of groups with permissions and such, and right now i have a function that looks like this
function hasPermission($user, $permission){
global $connection;
$sql = "SELECT * FROM admins WHERE `ID` = '". $user ."'";
$rs = $connection->query($sql);
if ($rs){
$user = $rs->fetch_array(MYSQL_ASSOC);
$userRank = $user['Rank'];
$sql = "SELECT * FROM `ranks' WHERE `RankName` = '". $userRank ."'";
$rs = $connection->query($sql);
if ($rs){
$rank = $rs->fetch_array(MYSQL_ASSOC);
if ($rank[$permission] == 1){
return true;
}
else{
return false;
}
}
}
else{
echo($connection->error);
}
}
Then when I call the function with the parameters set like this if (hasPermission($_SESSION['ID'], 'IsFullAccess') == true) it returns false, and I get my custom error message saying I don't have permission. And yes, in my database, the "IsFullAccess" column is set to 1 for that rank.
What am I doing wrong here?
After reading your code, it seems like you're not familiar with sql's JOIN:
your query looks something like this:
$sql= "SELECT r.$permission as p FROM admins a JOIN ranks r ON a.rank=r.RankName WHERE a.ID=$user";
$rs = $connection->query($sql);
if (!$rs)
return false;
$hasPermission = $rs->fetch_array(MYSQL_ASSOC);
return $hasPermission['p'];
(keep in mind sql injection)
Make sure that the db returns the result you expect before testing it within php
Try to use hasPermission($_SESSION['ID'], 'IsFullAccess') == 1) instead of hasPermission($_SESSION['ID'], 'IsFullAccess') == true). (true should be convert to 1)
Related
I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
Is it possible to re-write the code below, maybe even with an if (result > 0) statement, in just one line (or simply shorter)?
// a simple query that ALWAYS gets ONE table row as result
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
I've seen awesome, extremely reduced constructs like Ternary Operators (here and here - btw see the comments for even more reduced lines) putting 4-5 lines in one, so maybe there's something for single result SQL queries like the above.
You could shorten
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
to
$id = $this->db->query("SELECT id FROM mytable WHERE this = that")->fetch_object()->id;
but this, and the original code will emit errors, if any of the functions returns an unexpected response. Better to write:
$query = $this->db->query("SELECT id FROM mytable WHERE this = that");
if (!$query) {
error_log('query() failed');
return false;
}
$result = $query->fetch_object();
if (!$result) {
error_log('fetch_object() failed');
return false;
}
$id = $result->id;
I want to search my database to see if a user that is registering is using a username that is currently in my database. I have registered the same name about 5 times so it SHOULD return false but it returns true.
<?php
function registerUser($userName, $userPassword) {
$db = new dbinterface();
$db->connect();
// check for duplicate data
$checkduplicates = "SELECT * FROM usersexample WHERE $userName = :userName";
$myresult = mysql_query($checkduplicates);
if(mysql_num_rows($myresult) > 0){
echo $myresult;
return false;
}
?>
My table name is usersexample and the field i am searching is userName.
ANY and ALL help is appreciated!
Using mysql_num_rows in examples i get this warning:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource.
Use mysql_num_rows() to check the number of rows returned.
Sample:
$myresult = mysql_query($checkduplicates);
$rowcount = mysql_num_rows($myresult);
if($rowcount > 0)
{
// Account name already in use
}
You should try this...
if(mysql_num_rows($myresult) > 0) {
echo $myresult;
return false;
}
It will return false if there is a duplicate username.
$getduplicates = mysql_query("SELECT * FROM table WHERE username = $username");
$duplicates = mysql_num_rows($getduplicates);
if($duplicates){
echo "Uh oh someone already has that username";
}
else {
echo "Everything is allllllll good";
}
Please use prepared statements to avoid sql injection.
As you are using :userName in your SQL it seems you are trying to do this (is your
database class based on PDO by any chance?). The :userName part will be replaced
by your variable $userName when you do the bindValue.
Use count() in the database to count the number of records found,
the database knows best ;-)
$query = $db->prepare("SELECT count(*) AS no_found FROM usersexample WHERE userName = :userName");
$query->bindValue(':userName', $userName, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchObject();
if($result->no_found > 0)
{
return false;
}
Did you try:
$checkduplicates = "SELECT userName FROM usersexample
WHERE LOWER('".$userName."') = LOWER(userName)";
$myresult = mysql_query($checkduplicates)
if (!$myresult) {
die('Invalid query: ' . mysql_error());
} else {
$num_rows = mysql_num_rows($myresult);
if (!$num_rows) {
die('Invalid query: ' . mysql_error());
} else return ($num_rows == 0);
}
Please, sanitize user input to avoid SQL injection.
I don't know if you are doing something fancy I don't understand, but I would build the query like this:
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '$userName'";
Or this
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '".$userName."'";