php& mysql错误?

时间:2014-06-03 20:30:44

标签: php mysqli

enter image description here

我一直在努力解决这个问题,我是php和mysql的新手。有人可以指出错误的位置。我知道有mysql的certian版本但是我没有成功找到这个版本的正确解决方案。

以下是代码:

<?php
define('DB_HOST', 'localhost'); 
define('DB_USER', 'root'); 
define('DB_PASS', '');
define('DB_DATABASE', 'datadb');

$connection = mysqli_connect(DB_HOST, DB_USER,DB_PASS,DB_DATABASE);

// if there is an error number that exists, echo out message

if(mysqli_connect_errno())
{
    echo "error connecting to database:<br>"; 
    echo mysqli_connect_errno(); 
}


$db_selected = mysqli_select_db($connection,DB_DATABASE); 


function fetch_all($query)
{
$data = array();

$result = mysqli_query($connection,$query);
//iterate through the array
while($row = mysqli_fetch_assoc($result))
{
 $data[] = $row;
}
return $data;
}

function fetch_record($query)
{
$result = mysqli_query($query);
return mysqli_fetch_assoc($result);
}

?>

2 个答案:

答案 0 :(得分:2)

$connection变量在函数内部未定义。目前在您的fetch_all功能中。

您应该将其设置为全局:

function fetch_all($query) {
    global $connection;
    $data = array();    
    $result = mysqli_query($connection,$query);
    while($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    return $data;
}

或更好地将其添加为参数:

function fetch_all($connection, $query) {
    $data = array();
    $result = mysqli_query($connection,$query);
    while($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    return $data;
}

但我最喜欢的是写一堂课:

<?php

define('DB_HOST', 'localhost'); 
define('DB_USER', 'root'); 
define('DB_PASS', '');
define('DB_DATABASE', 'datadb');

class db {

    private $connection;
    private $db_selected;

    public function connect() { 
        $this->connection = mysqli_connect(DB_HOST, DB_USER,DB_PASS,DB_DATABASE);
        if(mysqli_connect_errno()) {
            echo "error connecting to database:<br>"; 
            echo mysqli_connect_errno(); 
        }
        $this->db_selected = mysqli_select_db($connection,DB_DATABASE);         
    }

    public function fetch_all($query) {
        $data = array();
        $result = mysqli_query($this->connection,$query);
        while($row = mysqli_fetch_assoc($result)) {
         $data[] = $row;
        }
        return $data;
    }

    public function fetch_record($query) {
        $result = mysqli_query($this->connection, $query);
        return mysqli_fetch_assoc($result);
    }
}

<强>用法:

$db = new db();
$db->connect();
$data = $db->fetch_all();
顺便说一下:如果你已经将mysqli_select_db传递给DB_DATABASE,你真的需要mysqli_connect吗?我不这么认为。

答案 1 :(得分:1)

由于您没有将$ connection传递给fetch_all,因此您应该在fetch_all函数中将其指定为global,即:

function fetch_all($query) {
  global $connection;
  $data = array();

  $result = mysqli_query($connection,$query);
  //iterate through the array
  while($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
  }
  return $data;
}