使用Include连接时如何从MySql数据库中获取?

时间:2017-04-21 03:58:12

标签: php mysql

我正在使用include连接文件来连接数据库。我的挑战是如何从数据库中获取这是卡在哪里。

include 'connection.php';

$sql = 'SELECT * FROM country';
$results = mysqli_query($sql);

1 个答案:

答案 0 :(得分:4)

假设您的connection.php包含

  <?php
        $con = mysqli_connect("localhost","my_user","my_password","my_db");

        if (mysqli_connect_errno())
        {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
  ?>

因此,在您的文件中,您使用include 'connection.php'来获取连接。现在使用include就像单页一样。然后你就像下面那样使用它

  require_once 'connection.php';

  $sql= 'SELECT * FROM country';
  $results = mysqli_query($con, $sql); # add connection string to query 

解释

当您添加此include 'connection.php';时,无论父文件( connection.php )文件(例如:变量,函数等等)的数据是否会出现在子文件中。< / p>

指向的链接

  1. In PHP, how does include() exactly work?
  2. Are PHP include paths relative to the file or the calling code?
  3. include, include_once, require or require_once?