gpt4 book ai didi

php - PDO 连接问题

转载 作者:行者123 更新时间:2023-11-29 01:36:34 25 4
gpt4 key购买 nike

我是新手所以不要粗鲁 :D

我有 3 个文件:database.php、init.php 和 user.php

这里是 init.php:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

require 'database.php';
require 'functions/user.php';
$errors = array();

这里是 database.php:

<?php
$db_host = "localhost";
$db_name = "xxxx";
$db_user = "xxxx";
$db_pw = "xxxx";

try {
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pw);
} catch(PDOException $e) {
die("Verbindung fehlgeschlagen: " . $e->getMessage());
}

这里是 user.php:

<?php
function userExists($user) {
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}

所以报错信息:

Notice: Undefined variable: conn in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 Fatal error: Call to a member function prepare() on null in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 

函数 userExists() 在另一个名为 login.php 的文件中被调用。在 login.php 中我已经需要 init.php。当我想登录时出现错误消息。

所以我希望你能帮助我。

谢谢

最佳答案

$conn 在您的函数中不可用,因为它在不同的范围内。将其作为参数传递或将其声明为全局变量。

function userExists($user, $conn){
// ...
}

function userExists($user){
global $conn;
// ...
}

关于php - PDO 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41440333/

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