如何正确使用PHP要求

编程入门 行业动态 更新时间:2024-10-25 00:26:59
本文介绍了如何正确使用PHP要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有3个文件:index.php,db.php(数据库)和functions.php

I have 3 files: index.php, db.php (database), and functions.php

下面是每个文件中的示例:

here is an example what is in each file:

database.php:

define ("DB_HOST", "localhost"); define ("DB_USER", "root"); define ("DB_PASS", "1234"); define ("DB_NAME", "test"); try { $dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST; $dbh = new PDO($dsn, DB_USER, DB_PASS); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }

index.php:

require $_SERVER['DOCUMENT_ROOT']."/config/db.php"; require $_SERVER['DOCUMENT_ROOT']."/config/functions.php"; if(isLoggedIn()) { echo "hi"; }

functions.php:

function isLoggedIn() { require $_SERVER['DOCUMENT_ROOT']."/config/db.php"; $stmt = $dbh->prepare("SELECT * FROM users...."); $stmt->execute(); }

我得到的错误是:

The error i get is:

注意:/var/www/config/database.php中已经定义了常量DB_HOST

Notice: Constant DB_HOST already defined in /var/www/config/database.php

我尝试过的事情:

我尝试在所有文件中将require替换为require_once,但是它给出的错误在这里:

I tried to replace require with require_once in all my files but the error that it gives is here:

致命错误:未捕获错误:在functions.php中调用成员函数prepare()上的空值

Fatal error: Uncaught Error: Call to a member function prepare() on null in functions.php

推荐答案

因此,由于这对您没有意义,所以我在这里的最后一个答案是您可以为彻底解决此问题而采取的措施的完整答案全部:

So, since it didn't make a sense to you my last answer here is a full answer of what you can do to get rid of this problem once for all:

db.php

<?php $host="localhost"; $user="root"; $password="1234"; $db="test"; try { $dbh = new PDO("mysql:host=$host;dbname=$db",$user,$password); } catch (PDOException $e) { die("DB ERROR: ". $e->getMessage()); } ?>

index.php

require_once $_SERVER['DOCUMENT_ROOT']."/config/db.php"; if(isLoggedIn($dbh)) { echo "hi"; }

functions.php

function isLoggedIn($dbh) { $stmt = $dbh->prepare("SELECT * FROM users...."); $stmt->execute(); } function anotherfunction($dbh) { $stmt = $dbh->prepare("SELECT * FROM others...."); $stmt->execute(); }

上述更正将为您省去处理需求的麻烦,您只需一次需要db.php,这样您现在就可以访问其变量并在需要时作为参数传递.

The above corrections will save you the pain of looking after the requires, you require the db.php once so that now you have access to its variable and pass as argument whenever needed.

注意:感谢Phil的卓有成效的评论和详尽的阐述.

Note: Thanks Phil for fruitful comments and good elaboration.

更多推荐

如何正确使用PHP要求

本文发布于:2023-06-04 08:32:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/493310.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何正确   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!