已连接页面PHP的mysqli_query连接 [英] mysqli_query connection for already connected page PHP

查看:72
本文介绍了已连接页面PHP的mysqli_query连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户已经登录了帐户仪表板的受保护页面,现在我要显示数据库中的某些表.这需要我使用mysqli_query.但是它显示错误.

The user is already logged in a protected page for account dashboard, now I want to show certain table from database. That required me to use mysqli_query. But it showing error.

db_connect.php

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
    header("Location: ../error.php?err=Unable to connect to MySQL");
    exit();
}

function.php

<?php


include_once 'psl-config.php';

function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name 
    $secure = SECURE;

    // This stops JavaScript being able to access the session id.
    $httponly = true;

    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }

    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);

    // Sets the session name to the one set above.
    session_name($session_name);

    session_start();            // Start the PHP session 
    session_regenerate_id();    // regenerated the session, delete the old one. 
}

function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT user_id, username, password, salt 
                  FROM *****
                                  WHERE email = ? LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password, $salt);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 
            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked 
                return false;
            } else {
                // Check if the password in the database matches 
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];

                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;

                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);

                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', $password . $user_browser);

                    // Login successful. 
                    return true;
                } else {
                    // Password is not correct 
                    // We record this attempt in the database 
                    $now = time();
                    if (!$mysqli->query("INSERT INTO login_attempts(user_id, time) 
                                    VALUES ('$user_id', '$now')")) {
                        header("Location: ../error.php?err=Database error: login_attempts");
                        exit();
                    }

                    return false;
                }
            }
        } else {
            // No user exists. 
            return false;
        }
    } else {
        // Could not create a prepared statement
        header("Location: ../error.php?err=Database error: cannot prepare statement");
        exit();
    }
}

function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time 
                                  FROM login_attempts 
                                  WHERE user_id = ? AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    } else {
        // Could not create a prepared statement
        header("Location: ../error.php?err=Database error: cannot prepare statement");
        exit();
    }
}

function login_check($mysqli) {
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password 
                      FROM ****** 
                      WHERE user_id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if ($login_check == $login_string) {
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Could not prepare statement
            header("Location: ../error.php?err=Database error: cannot prepare statement");
            exit();
        }
    } else {
        // Not logged in 
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&amp;', '&#038;', $url);
    $url = str_replace("'", '&#039;', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

'psl-config.php'包含带有DEFINE的连接记录

'psl-config.php' contains connection records with DEFINE

protected_pa​​ge.php已更新

    <?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Secure Login: Protected Page</title>
        <link rel="stylesheet" href="styles/main.css" />
    </head>
    <body>
        <?php if (login_check($mysqli) == true) : ?>
        <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
            <p>
                This is an example protected page.  To access this page, users
                must be logged in.  At some stage, we'll also check the role of
                the user, so pages will be able to determine the type of user
                authorised to access the page.
            </p>
            <?php
            $user_id =  htmlentities($_SESSION['user_id']);
         // Check connection
        if ($mysqli->connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
             // showing added broker
           $result= mysqli_query($mysqli,"SELECT accountno,*****,*****,***** FROM *** WHERE user_id = $user_id");
           echo "<table border='1'>
            <tr>
            <th>Account No</th>
            <th>******</th>
            <th>*****</th>
            <th>****</th>
            </tr>";

            while($row = mysqli_fetch_array($result))
            {
            echo "<tr>";
            echo "<td>" . $row['****'] . "</td>";
            echo "<td>" . $row['****'] . "</td>";
            echo "<td>" . $row['*****'] . "</td>";
            echo "<td>" . $row['*****'] . "</td>";
            echo "</tr>";
            }
            echo "</table>";
           $mysqli->close();
           ?>                   
            <p>Return to <a href="index.php">login page</a></p>
        <?php else : ?>
            <p>
                <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login</a>.
            </p>
        <?php endif; ?>
    </body>
</html>

这给我一个错误

警告:mysqli_fetch_array()期望参数1为mysqli_result,布尔值 此错误是针对protected_pa​​ge.php行代码生成的

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean This error was generated for the protected_page.php line code

while($ row = mysqli_fetch_array($ result))

while($row = mysqli_fetch_array($result))

尝试2:使用mysqli prepare语句: https://pastebin.com/2WzDg9zs

Attempt 2: With mysqli prepare statement: https://pastebin.com/2WzDg9zs

在此行"$ stmt-> bind_param('s',$ user_id);"

shows error on "Call to a member function bind_param() on boolean" on this line " $stmt->bind_param('s', $user_id); "

尝试3:解决了错误.表名错误.所以我纠正了.但是现在不在表上显示数据.与fetch()一起绘制表格.但是那里没有数据吗? 这是代码:

Attempt 3: Solved The Errors. Table name was wrong. So I corrected it. But now not showing data on table. with fetch() Its plotting the table. But no data in there? Here is the code:

        $stmt = $mysqli->prepare('SELECT accountno,accountname,cname,revenue,status FROM ***** WHERE user_id = ? '); 
        $stmt->bind_param('i', $user_id);  
       $stmt->bind_result($accountno ,$accountname, $cname, $revenue,$status);
        $stmt->execute();    // Execute the prepared query.
        echo "<table border='1'>
            <tr>
            <th>Account No</th>
            <th>Account Name</th>
            <th>Company Name</th>
            <th>Revenue</th>
            <th>Status</th>
            </tr>";

while($row = $stmt->fetch()) {

            echo "<tr>";
            echo "<td>" . $row['accountno'] . "</td>";
            echo "<td>" . $row['accountname'] . "</td>";
            echo "<td>" . $row['cname'] . "</td>";
            echo "<td>" . $row['revenue'] . "</td>";
            echo "<td>" . $row['status'] . "</td>";
            echo "</tr>";
            }
            $stmt->close();
            echo "</table>";

解决方案在这里找到:

推荐答案

$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

您需要首先连接到mysql数据库.然后您可以查看其是否已连接.并执行查询.

you need to first connect to the mysql database. then you can see if its connected. and execute the query.

if(!$link) {echo "Connection Error"; }

这篇关于已连接页面PHP的mysqli_query连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆