donglei2022 2018-06-21 05:31
浏览 120

sqli和数据库连接问题?

I have my PHP as following. These are two files in total

For 'dbh.php':

<?php

$server = "localhost";
$username = "root";
$password = "";
$name = "login_system";

$con = mysqli_connect("localhost","username","","login_system");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


?>

For 'index3.php':

<?php 
    include'dbh.php';
?>
<!DOCTYPE html>
<html>
    <head>
        <title> It is index 3</title>
    </head>
    <body>
    <?php
        global $con;
        $sql = "SELECT * FROM users;"; 
        $result = mysqli_query($con,$sql );
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0){
            while($row = mysqli_fetch_assoc(result)){
                echo $row['useruid'] . "<br>";
            }
        }
    ?>

    </body>
</html>

I got errors for executing this.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\phplesson\index3.php on line 13

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\phplesson\index3.php on line 14

Do this mean I get connection problems ? or other problems else?

Also, how can I fix it?

Appreciate for help!!

  • 写回答

1条回答 默认 最新

  • duanfei8399 2018-06-21 06:26
    关注

    Replace code of "dbh.php" by below:

    <?php
    $server = "localhost";
    $username = "root";
    $password = "";
    $db_name = "testc";
    $con = mysqli_connect($server,$username,$password,$db_name);
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    ?>
    

    Replace code of "index3.php" by below:

    <?php 
        include'db.php';
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <title> It is index 3</title>
        </head>
        <body>
        <?php
            $sql = "SELECT * FROM users;"; 
            $result = mysqli_query($con,$sql);
            $resultCheck = mysqli_num_rows($result);
            if ($resultCheck > 0){
                while($row = mysqli_fetch_assoc($result)){
                    echo $row['useruid'] . "<br>";
                }
            }
        ?>
        </body>
    </html>
    
    评论

报告相同问题?