【问题标题】:How to fetch from MySql Database when using Include connection?使用包含连接时如何从 MySql 数据库中获取?
【发布时间】:2017-09-17 22:13:30
【问题描述】:

我正在使用包含连接文件连接到数据库。我的挑战是如何从数据库中获取这是卡住的地方。

include 'connection.php';

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

【问题讨论】:

  • connection.php中设置连接$con并使用mysqli_query($con, $sql);

标签: php mysql


【解决方案1】:

假设您的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) 上的任何数据(例如:变量、函数等)都会传给子文件。


参考链接

  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?

【讨论】:

  • 你应该在这里使用include_once而不是include。最好使用require_once,因为查询必须存在connection.php 才能工作。
  • 正在进行中..但您在发布之前添加评论;)
猜你喜欢
  • 2015-02-04
  • 1970-01-01
  • 2016-10-12
  • 2011-05-28
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2018-03-25
相关资源
最近更新 更多