Tuesday, 28 August 2018

MySQLi Query does not return results correctly

I'm trying to switch my website over to MySQLi and I'm following the W3schools MySQLi guide to do so. I've hit a roadblock, though. I have a function to check if a specified user is an admin on the site. I've put echo in various spots to find where the issue is, and I've figured out that it most likely doesn't see the user. $username is set to the variable $user. Here's the whole code block (part of connect.php:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if(!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

session_start();
if(!isset($_SESSION["user_login"])) {
    $user = "";
} else {
    $user = $_SESSION["user_login"];
}

//functions
function isAdmin($username) {
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "lark";
    $conn = mysqli_connect($servername, $username, $password, $dbname);

    $sql_get_is_admin = "SELECT * FROM users WHERE username='$username' LIMIT 1";
    $get_is_admin = mysqli_query($conn, $sql_get_is_admin);

    if(mysqli_num_rows($get_is_admin) > 0) {
        echo "num_rows";
        while ($row = mysqli_fetch_assoc($get_is_admin)) {
            $is_admin_bool = $row['admin'];
            echo "while";
            if($is_admin_bool == 0){
                return false;
            } elseif ($is_admin_bool == 1) {
                return true;
            }
        }

    } else {
        echo "not found.";
    }
}
?>

Here's the code I used to test the $user variable:
<?php
include("connect.php");
?>
<div class="main">
<h1>Welcome back, <?php echo $user; ?></h1>
foo
<?php
/*if(isAdmin($user) == true) {
    echo   "<div style='display: table-cell;' class='rightcell'>
                <h3 style='color: #000;'>Admin Tools</h3>
                <a href='userlist.php' target='_blank'>Userlist</a>
            </div>";
} else {
} */

echo isAdmin($user);
?>
</div>

I also had to reconnect to the database or else I'd get this error on the site:
Notice: Undefined variable: conn in C:\xampp\htdocs\lark\connect.php on line 33

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\lark\connect.php on line 33

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\lark\connect.php on line 35 not found.

If I fix it so there's no error, it just says "not found."

You don't have $conn in your function, it is commented out.
function isAdmin($username) {
    /*$servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "lark";
    $conn = mysqli_connect($servername, $username, $password, $dbname);*/

0 comments:

Post a Comment