我必须为一个函数连接两次数据库

时间:2018-04-05 06:55:05

标签: php database

在文档的开头,我调用include database.php,其中包含

$database = new mysqli('localhost', 'root', 'root', 'dbname', 3306);

然而,当我尝试通过函数更新数据库信息时,$ database变量似乎不存在,所以我必须再次调用它

有没有解决方案?

功能代码:

<?php
            include 'database.php';        

?>

。 。

<?php 


   function roll() {

$bet= $_POST["bet"];
    $_SESSION['dice1']=rand(1,6);
    $_SESSION['dice2']=rand(1,6);
    $total=$_SESSION['dice1']+$_SESSION['dice2'];



if($total==2) $win=$bet*2;
 else if($total==3 || $total==4) $win=0;
  else if($total==10 || $total==11) $win=$bet;
   else if($total==12) $win=$bet*4;
    else if($total==0) $win=0;
else $win=$bet-(2*$bet);


  //  $database = new mysqli('localhost', 'root', 'root', 'dbname', 3306);
    $database->query("UPDATE users SET balance=balance+'$win' WHERE name='$_SESSION[username]'");

}

1 个答案:

答案 0 :(得分:-1)

 # And this is my database connection file:
    <?php
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "test";

                // Create connection
                $conn = new mysqli($servername, $username, $password, $dbname);

                // Check connection
                if ($conn->connect_error) {
                     die("Connection failed: " . $conn->connect_error);
                } 

            $conn->close();
        ?>

 # This is my login page:
        <?php 
            include ('database.php');
            include('password_hash_lib/password.php');

            if (isset($_POST['data']))
            {
                $data = $_POST['data'];
                $auth = json_decode($data);
                $user_email = $auth->Email;
                $user_pass = $auth->Password;
                authenticate($user_email, $user_pass);
            }

            function authenticate($Email, $Password)
            {   
                 global $conn;
                 $HashedPassword = password_hash($Password, PASSWORD_DEFAULT);        
                 $sql = "SELECT * FROM app_users WHERE user_email='$Email'"; 
                 $result = $conn->query($sql);
                 $User = $result->fetch_object();

                if ($User->user_email == '')
                {
                    header("Location: login-page.html?msg=failed");
                }

                if (password_verify($Password, $User->user_password_hash))
                {
                    $_SESSION["user_auth_details"] = $User->user_id . "+" . $User->user_email . '+' . $User->user_name . "+" . $User->user_display_image . "+" . $User->user_display_name;
                    header("Location:" . $_SESSION['page_url']);
                }
                 else {
                    header("Location: login-page.html?msg=failed");

                 }
            }

        ?>