简体   繁体   中英

mysqli_num_rows doesn't show desired results

I have a 'users' table in my Database (currently 4 users) that contains different roles (1 = user, 2= admin, 3= moderator). I want to show some lines of my php script only to admins and moderators, so I made this query: (I know it is not secure)

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$stuff = 'SELECT * FROM `users` WHERE role > 0';
$result = mysqli_query($conn, $stuff);

This query list all users with the role over 0.

require_once('link_to_script.php');
if (mysqli_num_rows($result) >1){
echo "Admin area";
}else{
echo "No Permissions";
}

This should be self explaining (only show "Admin area" to users with role higher than 1)

I don't know what my mistake is and I hope someone could help me a little bit :)

You can use IN in your SQL Query, For example if you need admin and moderator use the following

 SELECT * FROM `users` WHERE role IN ('2','3')

mysqli_num_rows returning number of rows in result set.

if (mysqli_num_rows($result)){
   echo "Admin and moderator area";
}else{
  echo "No Permissions";
}

You are saying you want more than 1 row, you probably want to say more than 0 rows or just 1 row...

if (mysqli_num_rows($result) >1){

Should be

if (mysqli_num_rows($result) >0){

or

if (mysqli_num_rows($result) == 1){

As for I know it is not secure - as there are no bound parameters, the SQL cannot be influenced by any input and so there is not problems with security in this case. BUT you will probably want to add in the logged in user at some point, this should be done with prepared statements.

I'am grabing the current user now with:

$userID = $page->users->currentUserId();
$stuff = 'SELECT role FROM `users` WHERE id = $userID';
$result = mysqli_query($conn, $stuff;
if (mysqli_num_rows($result) >2){
....

Grabbing of the current userID is working but how can i compare it with the the role, that is needed ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM