mysqli的PHP变量范围问题

时间:2014-11-13 06:26:54

标签: php mysqli

我还在学习PHP,而我正试图解决这个错误。 根据{{​​3}}我的代码是正确的,但这是我的代码,这是我收到的错误:

$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

function get_demos(){
    $result = mysqli_query($con,"SELECT * FROM demos");
    if(!$result)
    {
        die("Invalid query ".mysqli_error($con));
    }
    return $result;
}

get_demos();
  

警告:mysqli_query()要求参数1为mysqli,在第10行的/home/content/83/11483383/html/php/db.php中给出null

     

警告:mysqli_error()期望参数1为mysqli,null给定   在/home/content/83/11483383/html/php/db.php第13行无效的查询

我做错了什么?

感谢。

4 个答案:

答案 0 :(得分:2)

你应该尝试,

$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

function get_demos($con){
    $result = mysqli_query($con,"SELECT * FROM demos");
    if(!$result)
    {
        die("Invalid query ".mysqli_error($con));
    }
    return $result;
}

get_demos($con);

答案 1 :(得分:2)

您没有声明已设置变量$con

试试这个

$con = mysqli_connect('localhost', 'root', '');
    mysqli_select_db($con, 'databse_name_here') or die ('Failed to connect to MySQL: ' . mysqli_connect_error()); 


function get_demos($con){
    $result = mysqli_query($con,"SELECT * FROM users");
    if(!$result)
    {
        die("Invalid query ".mysqli_error($con));
    }
    return $result;
}

get_demos($con);

答案 2 :(得分:2)

您必须将连接传递给您的函数。如果你不想每次都使用单例模式来做它,那么它总是在范围内。

class DBCon {

private static $_instance = null;

 private function __construct() {
    $_instance = mysqli_connect("IP","username","passowrd","dbname");
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
 }

 public static function get() {
   if(is_null(self::$_instance)) {
      self::$_instance = new DBCon();
   }
   return self::$_instance;
 }
}

并在您的代码中使用它:

function get_demos(){
    $result = mysqli_query(DBCon::get(),"SELECT * FROM demos");
    if(!$result)
    {
        die("Invalid query ".mysqli_error(DBCon::get()));
    }
    return $result;
}

答案 3 :(得分:-1)

在提出问题后我找到了解决方案:

$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

function get_demos(){
    global $con;
    $result = mysqli_query($con,"SELECT * FROM demos");
    if(!$result)
    {
        die("Invalid query ".mysqli_error($con));
    }
    return $result;
}

get_demos();

添加全球$ con。