gpt4 book ai didi

PHP 数据库类加载行函数 (OOP)

转载 作者:行者123 更新时间:2023-11-29 13:50:11 26 4
gpt4 key购买 nike

我想打印“forum_question”表的所有内容。我究竟做错了什么?无论如何,我都会收到消息“没有找到!”,但我确信 $db->connect 确实有效,因此它必须与查询或 loadRows 函数相关。

这是我的数据库类:

<?php
class Database {
private $host;
private $user;
private $password;
private $rows;
private $result;
private $dbName;
private $connection;
private $isReady;

public function __construct() {
$this->result = null;
$this->isReady = false;
}

/* setters */
public function setHost($host){ $this->host = $host; }
public function setUser($user){ $this->user = $user; }
public function setPassword($password){ $this->password = $password; }
public function setDbName($dbName){ $this->dbName = $dbName; }

/* Interface functions */
public function initiate($host=null,$user=null,$password=null,$dbName=null) {
if(isset($host,$user,$password,$dbName)==false) {
die("Please provide require settings.");
}
$this->setHost($host);
$this->setUser($user);
$this->setPassword($password);
$this->setDbName($dbName);
$this->isReady = true;
}

public function connect() {
if($this->isReady==false) {
die("Not ready to connect, please initiate connection");
}
$connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
$this->connection = new PDO($connection_string, $this->user, $this->password);
$this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
}

public function disconnect() {
$this->connection = null;
$this->isReady = false;
$this->setHost = null;
$this->setUser = null;
$this->setPassword = null;
$this->setDbName = null;
}

public function query($sql) {
$this->result = $this->connection->query($sql);
}

public function countRows() {
return $this->result->rowCount(); }

public function loadRows() {
if(!$this->result) die("Nothing found!");
$this->rows = array();
foreach ($this->result as $row) {
$this->rows[] = $row;
}
return $this->rows;
}

} // End of Database class
?>

这是我的索引文件:

<?php

require_once 'class_database.php';

$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();

$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();


?>

最佳答案

为什么不尝试使用不同的连接脚本?例如:

<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
printf("Connection failed: %s \n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");

工作正常,您所要做的就是:

<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();

假设您将连接脚本保存在文件“connection.php”中。

关于PHP 数据库类加载行函数 (OOP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com