gpt4 book ai didi

PHP SQL 代码优化

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

我正在学习面向对象的PHP。现在我的任务是建立联系。我想展示我的代码并请求您提供一些优化支持。也许有一些完全错误的理解。我不希望如此。我想改进我的设计。实际上,常量当然具有正确的值。十分感谢! :)

//index.php

<?php
require( dirname( __FILE__ ) . '/config.php' );
new db(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

//config.php

<?php
define('DB_HOST', 'host');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');

if (!defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');

require_once(ABSPATH . '/includes/classes/db.class.php');
?>

//db.class.php

<?php
class db
{
protected $db_host;
protected $db_user;
protected $db_password;
protected $db_name;

function __construct($dbHost, $dbUser, $dbPassword, $dbName)
{
global $mysqli;

$this -> db_host = $dbHost;
$this -> db_user = $dbUser;
$this -> db_password = $dbPassword;
$this -> db_name = $dbName;

$this -> mysqli = new mysqli($this -> db_host, $this -> db_user, $this -> db_password, $this -> db_name);
$mysqli = $this -> mysqli;
}
}
?>

最佳答案

这是我不久前在数据库层发现的一些技巧

将连接定义为静态变量,以避免多次连接

static $connection;

尝试连接数据库,如果尚未建立连接,则仅创建一次连接

if(!isset($connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}

如果连接不成功,处理错误

if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}

最终返回连接

return $connection;

更多信息:https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17

关于PHP SQL 代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161820/

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