简单的mySQLi选择一个数组

时间:2014-09-20 04:45:52

标签: php mysqli

从我在网上找到的教程构建。

我试图从'项目中选择所有项目'表并创建一个数组。不确定这是如何工作的。这$result = $this->connection->query($q);是造成问题的原因。

<?php
//DB.class.php

class DB {

    protected $db_name = 'dbname';
    protected $db_user = 'user';
    protected $db_pass = 'pass';
    protected $db_host = 'localhost';
    protected $connection;

    public function connect() {
    $connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);

    // check connection
    if ($connection->connect_error) {
      trigger_error('Database connection failed: '  . $connection->connect_error, E_USER_ERROR);
    }

    }

  public function resultToArray($result) {
    $rows = array();
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
  }

  public function sel($table) {
    $q = "SELECT * FROM $table";
    $result = $this->connection->query($q);
    $rows = $this->resultToArray($result);

    return $rows;

    $result->free();

  }

}

2 个答案:

答案 0 :(得分:1)

制作像

这样的构造函数
public $mysqli;
    public function __construct()
    {
        $mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        $this->mysqli = $mysqli;
    }

public function sel($table,$whr)
    {
    $query = "SELECT * FROM ".$table." where id='$whr'";
    $result = $this->mysqli->query($query);
    $total = array();
    while($row = $result->fetch_assoc()){
            //print_r($row);die;
         $total[] = $row;
    }//print_r($total);die;
    return $total;
    }

答案 1 :(得分:0)

我认为你应该设置一个构造函数,但是如果你不想要,只需先返回它的一个实例并设置你的$this->connection属性而不是$connection(正常变量):

class DB {

    protected $db_name = 'test';
    protected $db_user = 'test';
    protected $db_pass = 'test';
    protected $db_host = 'localhost';
    protected $connection;

    public function connect() {
        $this->connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
        // ^^ this one, not $connection
    // check connection

    if ($this->connection->connect_error) {
      trigger_error('Database connection failed: '  . $connection->connect_error, E_USER_ERROR);
    }

        return $this->connection; // then return this
    }

  public function resultToArray($result) {
    $rows = array();
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
  }

  public function sel($table) {
    $q = "SELECT * FROM $table";

    $result = $this->connection->query($q);
                  // ^ so that if you call this, you have the mysqli object
    $rows = $this->resultToArray($result);

    return $rows;

    $result->free();

  }

}

$db = new DB(); // instantite,
$db->connect(); // then connect, shouldn't have to have this if you put the connection automatically on construct
$result = $db->sel('users'); // feed a valid existing table name
echo '<pre>';
print_r($result);