2.开发步骤 (1)创建Sql.php文件,用来封装数据库操作类。 (2)创建构造方法,初始化数据库信息。 (3)创建connect0方法连接数据库。 (4)封装执行读写操作的方法。 (5)在浏览器中查看运行结果。
时间: 2023-12-06 19:39:30 浏览: 34
好的,以下是更详细的步骤:
(1) 创建Sql.php文件
在你的项目中创建一个名为Sql.php的文件,用于封装数据库操作类。
(2) 创建构造方法
在Sql.php文件中创建一个构造方法,用于初始化数据库信息。你需要传递以下参数:
- 主机名
- 用户名
- 密码
- 数据库名
```
class Sql {
private $host;
private $username;
private $password;
private $dbname;
public function __construct($host, $username, $password, $dbname) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
}
}
```
(3) 创建connect0方法
在Sql.php文件中创建一个connect0方法,用于连接数据库。连接成功后,返回连接对象。
```
class Sql {
private $host;
private $username;
private $password;
private $dbname;
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
}
public function connect0() {
$this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->dbname);
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
return $this->conn;
}
}
```
(4) 封装执行读写操作的方法
在Sql.php文件中创建一个execute方法,用于执行读写操作。你需要传递以下参数:
- SQL语句
- 是否为查询语句
如果是查询语句,返回查询结果。如果是更新语句,返回受影响的行数。
```
class Sql {
private $host;
private $username;
private $password;
private $dbname;
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
}
public function connect0() {
$this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->dbname);
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
return $this->conn;
}
public function execute($sql, $is_query) {
$result = mysqli_query($this->conn, $sql);
if (!$result) {
die("Error executing query: " . mysqli_error($this->conn));
}
if ($is_query) {
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
} else {
return mysqli_affected_rows($this->conn);
}
}
}
```
(5) 在浏览器中查看运行结果
在你的项目中创建一个test.php文件,用于测试Sql类的功能。在test.php文件中,先实例化Sql类,然后连接数据库,并执行一个查询语句。
```
require_once('Sql.php');
$sql = new Sql('localhost', 'username', 'password', 'dbname');
$conn = $sql->connect0();
$result = $sql->execute("SELECT * FROM users", true);
var_dump($result);
```
在浏览器中打开test.php文件,你应该能够看到从数据库中查询到的用户数据。