我刚刚开始学习面向对象编程的概念,并且我已经用函数编写了这个类.
它工作正常,但我很想知道我是否正确地做到了这一点……
这是我的代码:
class Database{ const DB_HOSTNAME = 'localhost'; const DB_USERNAME = 'root'; const DB_PASSWORD = 'password'; const DB_NAME = 'shop'; protected $_db_connect; protected $_sql; protected $_result; protected $_row; function db_connect(){ $this->_db_connect = MysqL_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD) or die(MysqL_error()); } function slect_db(){ MysqL_select_db(self::DB_NAME) or die(MysqL_error()); } function sql(){ $this->_sql = 'SELECT * FROM users'; } function query(){ $this->_result = MysqL_query($this->_sql); } function fetch_array(){ while($this->_row = MysqL_fetch_array($this->_result)){ $username = $this->_row['user_USERNAME']; echo "<ul>"; echo "<li>".$username."</li>"; echo "</ul>"; } } function db_close(){ MysqL_close($this->_db_connect); } } $database = new Database(); $database->db_connect(); $database->slect_db(); $database->sql(); $database->query(); $database->fetch_array(); $database->db_close();
请使用PDO或MysqLi,因为它更安全,并且如上所述不推荐使用MysqL_ *函数,我提供了一些使用PDO的通用代码来帮助您进行新的冒险.正如评论中所述,如果你正在寻找一个面向对象的设计,你真的不应该回应数据,你应该做的是在你进行查询之后,返回你提取的行并从那里使用一些东西比如foreach循环然后显示你的数据.以这种方式执行数据库类还将确保不会立即打开多个数据库连接!请注意,此代码仅供您参考,应在生产中使用之前进行测试或任何实时测试.
原文链接:https://www.f2er.com/php/136079.html<?PHP //Enter your database connection details here. $host = 'localhost'; //HOST NAME. $db_name = 'databasename'; //Database Name $db_username = 'root'; //Database Username $db_password = ''; //Database Password try { $pdo = new PDO('MysqL:host='. $host .';dbname='.$db_name,$db_username,$db_password); } catch (PDOException $e) { exit('Error Connecting To DataBase'); } ?>
database.class.PHP:
<?PHP class database { function __construct($pdo) { $this->pdo = $pdo; } function getData() { $query = $this->pdo->prepare('SELECT * FROM database'); $query->execute(); return $query->fetchAll(); } } ?>
<?PHP require_once 'config.PHP'; require_once 'database.class.PHP'; $db = new database($pdo); $rows = $db->getData(); ?>