[英]OOP PHP Database results to Array
我是oop php的新手,我正在嘗試編寫一個irc php。
我想做的是:我想查詢數據庫,從數據庫中獲取結果,並將其放入程序內部的數組中。
我嘗試制作一個新函數來執行任務,並在__construct函數中對其進行了調用。
我已經縮短了代碼,但是看起來幾乎是這樣的:
任何想法都值得贊賞。
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
function __construct()
{
//create new instance of mysql connection
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$this->database_fetch();
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row();
}
}
function main()
{
print_r($array);
}
}
$bot = new IRCBot();
首先,您需要修復構造函數中的錯誤,您可以將其修改為:
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
echo $this->conn->host_info . "\n";
}
$conn
替換$mysqli
,因為您的鏈接標識符是$conn
而不是$mysqli
database_fetch()
。 $conn
用作屬性。 現在,您需要將database_fetch()
方法修改為:
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
在這里,您需要在mysqli_query()
傳遞添加第一個參數,該參數應該是鏈接標識符/數據庫連接。
其次,您需要使用return從此函數獲取結果。
最后,您需要將main()
方法修改為:
function main()
{
$data = $this->database_fetch();
print_r($data);
}
database_fetch()
方法,然后在所需的位置打印數據。 變化
1)將 if ($mysqli->connect_errno)
)更改為if ($conn->connect_errno)
2)更改$array[] = $row();
到$array[] = $row;
3)添加return $array;
在函數database_fetch()
4)在main()
函數而不是構造函數中調用database_fetch()
函數。
5)在mysqli_query()
)中添加$this->conn
(感謝@devpro指出)。
更新的代碼
<?php
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
public $conn;
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
return $array;
}
function main()
{
$data = $this->database_fetch();
print_r($data);
}
}
快速開始
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.