使用 PHP OOP 概念连接到 MySQL 数据库 [英] Connect to MySQL database using PHP OOP concept
问题描述
我正在编写一个类和一些函数来连接到数据库并从表中检索信息.我浏览了以前标题相似的帖子,但其中大多数是使用 mysql 函数编写的,而我正在使用 mysqli 函数.
I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
我希望有人能够完成这个简单的脚本,并让我知道我在哪里犯了错误.
I want somebody who can go through this simple script and let me know where I am making my mistake.
这是我的class.connect.php
:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
这是我的index.php
:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
我收到错误消息,说查询数据库时出错
.
推荐答案
问题在于:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
或者这个:
while($array = $connection->fetch($query))
因为您正在使用查询的结果再次查询.基本上,您正在做:
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
并且您收到错误消息,因为 $r 不是查询字符串.当它转换为字符串时,它是一个1"(来自您的其他评论).
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
尝试将函数更改为(更改变量名称以便您可以看到差异):
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
或者直接调用函数.
这篇关于使用 PHP OOP 概念连接到 MySQL 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!