小白求指点:这样的代码结构怎么样优化呢?
我是这样设计的:一个是数据库连接文件 db.conn.php 一个自定义函数文件 config.inc.php
db.conn.php:
<?php$db_host = 'localhost';$db_user = '*****';$db_password = '*******';$db_database = '******';$conn = new mysqli($db_host, $db_user, $db_password, $db_database);mysqli_query($conn, "set names 'utf8'"); if(mysqli_connect_errno()){die('数据库连接失败: ' . mysqli_connect_error());}$site_data = $conn->query("SELECT * FROM `dh_member_control` WHERE `id`=1");$site = mysqli_fetch_array($site_data);?>
config.inc.php:
function marrbase(){if(isset($_COOKIE["uname"]) && isset($_COOKIE["uid"])){global $mbase;global $conn;$mql = "select * from dh_member where `id`=" . $_COOKIE["uid"] . " and `mck`=1";$mbase_data = mysqli_query($conn, $mql);$mbase = mysqli_fetch_array($mbase_data);}else{exit();}}function login_log($muid){if (empty($muid)){exit();}else {global $conn;$lql = "INSERT INTO `dh_mllog` (`uid`,`ltime`,`lip`,`lptxt`) VALUES (". $muid .",'". date("Y-m-d H:i:s") ."','". getIPaddress() ."','". getIPS138(getIPaddress()) ."')" ;if (!mysqli_query($conn, $lql)){die(mysqli_error());exit();}}}function memberislogin($back = NULL){if(!isset($_COOKIE["uname"]) || !isset($_COOKIE["uid"])){echo "<script>alert('没有登录');window.location.href=\"/member/login.php?backurl=". $back ."\";</script>"; exit();}else {global $conn;$login_check = mysqli_query ("SELECT * FROM `dh_member` WHERE `id`=". $_COOKIE["uid"] ." AND `mck`=1");if(!mysqli_num_rows($login_check)){echo "<script>window.location.href=\"/member/login.php?backurl=". $back ."\"</script>"; exit();}}}.....等等自定义函数
在用户前台 引用进这些文件 然后进行输出交互等操作..
这里面我目前就觉着 我每次自定义个函数 都要 global $conn 来引用,有没有更好的办法来设计?
整个网页设计有没有更好的设计方式呢(CMS就不要推荐了)
求做过大项目的大神指点指点..
回复讨论(解决方案)
从 mysqli 继承一个 db 类
提供:
count 属性,用于返回影响的条数
fetch 方法,传入查询指令,返回一维数组
fetchall 方法,传入查询指令,返回二维数组
exec 方法,用于执行非查询类指令
基本就够了
学会封装代码,将mysql模块封装,其它需要用的地方,引用这个文件,直接调用封装的接口。
从 mysqli 继承一个 db 类
提供:
count 属性,用于返回影响的条数
fetch 方法,传入查询指令,返回一维数组
fetchall 方法,传入查询指令,返回二维数组
exec 方法,用于执行非查询类指令
基本就够了
谢谢两位大神啊 我之前看过有这样的资源 就是常用数据库操作类 是这样类似的用途么
fetchall 方法,传入查询指令,返回二维数组
exec 方法,用于执行非查询类指令
这两个 我有点不太理解 返回二维数组 ,一般在什么情况下会用到啊
用于执行非查询类指令
学会封装代码,将mysql模块封装,其它需要用的地方,引用这个文件,直接调用封装的接口。
谢谢啊,有没有实例代码啊?
你总是有查询出多条记录的情况吧?比如文章列表
最简单的写法
class db extends mysqli { function __construct() { parent::__construct('localhost', '用户名', '口令', '数据库'); $this->query('set names utf8'); } function fetch($sql) { $rs = $this->query($sql); return $rs->fetch_assoc(); } function fetchall($sql) { $rs = $this->query($sql); while($row = $rs->fetch_assoc()) { $res[] = $row; } return $res; } funetion exec($sql) { return $this->query($sql); }}
例
$p = new db;print_r($p->fetch("select * from a"));print_r($p->fetchall("select * from a"));
由于是继承 mysqli 类的,所以 mysqli 类的方法、属性都存在,不必一一抄写
你的 INSERT INTO `dh_mllog`.... 不就是非查询类的指令吗
你的 INSERT INTO `dh_mllog`.... 不就是非查询类的指令吗
你总是有查询出多条记录的情况吧?比如文章列表
最简单的写法
class db extends mysqli { function __construct() { parent::__construct('localhost', '用户名', '口令', '数据库'); $this->query('set names utf8'); } function fetch($sql) { $rs = $this->query($sql); return $rs->fetch_assoc(); } function fetchall($sql) { $rs = $this->query($sql); while($row = $rs->fetch_assoc()) { $res[] = $row; } return $res; } funetion exec($sql) { return $this->query($sql); }}
例
$p = new db;print_r($p->fetch("select * from a"));print_r($p->fetchall("select * from a"));
由于是继承 mysqli 类的,所以 mysqli 类的方法、属性都存在,不必一一抄写
谢谢版主
你的 INSERT INTO `dh_mllog`.... 不就是非查询类的指令吗
你总是有查询出多条记录的情况吧?比如文章列表
最简单的写法
class db extends mysqli { function __construct() { parent::__construct('localhost', '用户名', '口令', '数据库'); $this->query('set names utf8'); } function fetch($sql) { $rs = $this->query($sql); return $rs->fetch_assoc(); } function fetchall($sql) { $rs = $this->query($sql); while($row = $rs->fetch_assoc()) { $res[] = $row; } return $res; } funetion exec($sql) { return $this->query($sql); }}
例
$p = new db;print_r($p->fetch("select * from a"));print_r($p->fetchall("select * from a"));
由于是继承 mysqli 类的,所以 mysqli 类的方法、属性都存在,不必一一抄写
谢谢版主
弱弱的问下啊,下面这段,按你这样的类方法调用该怎么改写啊?
<?$hot_vip_data = $conn->query("SELECT * FROM dh_member WHERE `mck`=1 AND `photo`<>'/images/nan.png' AND `photo`<>'/images/nv.png' ORDER BY `mpower` DESC,`cktime` DESC LIMIT 1,12");$i=1;while ($hot_vip = mysqli_fetch_array($hot_vip_data)){if ($i % 6 == 0){$last=" class=\"last\"";}else{$last="";}$i++;?><li <? echo $last;?> onclick="javascript:location.href='/display/?<? echo $hot_vip["id"]?>.html'"><div class="vpc"><img src="/static/imghw/default1.png" data-src="<? echo $hot_vip[" class="lazy" photo"]? alt="小白求指点:这样的代码结构怎么样优化呢?" >" /></div><div class="vpn"><? if (strlen($hot_vip["unick"])>4){echo cut_str($hot_vip["unick"],4);}else{echo $hot_vip["unick"];}if ($hot_vip["mpower"]==2){ echo " <a href=\"/vip/\" title=\"初遇会员\"><img src="/static/imghw/default1.png" data-src="<? echo $hvip_data[" class="lazy" src=\"/images/v.png\" / alt="小白求指点:这样的代码结构怎么样优化呢?" ></a>";} ?></div><div class="vpt"><? $timediff = strtotime (date("y-m-d")) - strtotime($hot_vip["sri"]) ;echo intval($timediff/(86400*365)) . "岁 ";echo $hot_vip["add"];?></div></li><? }?>
这样改写么?
<?$hvip = new db;$hvip_data = $hvip->fetchall("SELECT * FROM dh_member WHERE `mck`=1 AND `photo`<>'/images/nan.png' AND `photo`<>'/images/nv.png' ORDER BY `mpower` DESC,`cktime` DESC LIMIT 1,12");$i=1;while ($hvip_data){if ($i % 6 == 0){$last = " class=\"last\"";}else{$last = "";}$i++;?><li <? echo $last;?> onclick="javascript:location.href='/display/?<? echo $hvip_data["id"]?>.html'"><div class="vpc"><img src="/static/imghw/default1.png" data-src="<? echo $hvip_data[" class="lazy" photo"]? alt="小白求指点:这样的代码结构怎么样优化呢?" >" /></div><div class="vpn"><? if (strlen($hvip_data["unick"])>4){echo cut_str($hvip_data["unick"],4);}else{echo $hvip_data["unick"];}if ($hvip_data["mpower"]==2){ echo " <a href=\"/vip/\" title=\"初遇会员\"><img src="/static/imghw/default1.png" data-src="<? echo $hvip_data[" class="lazy" src=\"/images/v.png\" / alt="小白求指点:这样的代码结构怎么样优化呢?" ></a>";} ?></div><div class="vpt"><? $timediff = strtotime (date("y-m-d")) - strtotime($hvip_data["sri"]) ;echo intval($timediff/(86400*365)) . "岁 ";echo $hvip_data["add"];?></div></li><? }?>
<?$hvip = new db;$sql = $hvip->fetchall("SELECT * FROM dh_member WHERE `mck`=1 AND `photo`<>'/images/nan.png' AND `photo`<>'/images/nv.png' ORDER BY `mpower` DESC,`cktime` DESC LIMIT 1,12";foreach($hvip->fetchall($sql) as $i=>$hvip_data) { if (($i+1) % 6 == 0) $last = " class=\"last\""; else $last = "";?><li <? echo $last;?> onclick="javascript:location.href='/display/?<? echo $hvip_data["id"]?>.html'"><div class="vpc"><img src="/static/imghw/default1.png" data-src="<? echo $hvip_data[" class="lazy" photo"]? alt="小白求指点:这样的代码结构怎么样优化呢?" >" /></div><div class="vpn"><? if (strlen($hvip_data["unick"])>4){echo cut_str($hvip_data["unick"],4);}else{echo $hvip_data["unick"];}if ($hvip_data["mpower"]==2){ echo " <a href=\"/vip/\" title=\"初遇会员\"><img src="/static/imghw/default1.png" data-src="<? echo $hvip_data[" class="lazy" src=\"/images/v.png\" / alt="小白求指点:这样的代码结构怎么样优化呢?" ></a>";} ?></div><div class="vpt"><? $timediff = strtotime (date("y-m-d")) - strtotime($hvip_data["sri"]) ;echo intval($timediff/(86400*365)) . "岁 ";echo $hvip_data["add"];?></div></li><? }?>
<?$hvip = new db;$sql = $hvip->fetchall("SELECT * FROM dh_member WHERE `mck`=1 AND `photo`<>'/images/nan.png' AND `photo`<>'/images/nv.png' ORDER BY `mpower` DESC,`cktime` DESC LIMIT 1,12";foreach($hvip->fetchall($sql) as $i=>$hvip_data) { if (($i+1) % 6 == 0) $last = " class=\"last\""; else $last = "";?><li <? echo $last;?> onclick="javascript:location.href='/display/?<? echo $hvip_data["id"]?>.html'"><div class="vpc"><img src="/static/imghw/default1.png" data-src="<? echo $hvip_data[" class="lazy" photo"]? alt="小白求指点:这样的代码结构怎么样优化呢?" >" /></div><div class="vpn"><? if (strlen($hvip_data["unick"])>4){echo cut_str($hvip_data["unick"],4);}else{echo $hvip_data["unick"];}if ($hvip_data["mpower"]==2){ echo " <a href=\"/vip/\" title=\"初遇会员\"><img src=\"/images/v.png\" / alt="小白求指点:这样的代码结构怎么样优化呢?" ></a>";} ?></div><div class="vpt"><? $timediff = strtotime (date("y-m-d")) - strtotime($hvip_data["sri"]) ;echo intval($timediff/(86400*365)) . "岁 ";echo $hvip_data["add"];?></div></li><? }?>
谢谢版主

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.
