mysql - 使用 PDO 的 undefined variable

标签 mysql pdo php

<分区>

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

我是 PDO 的新手,我目前正在尝试将我所有的 mysql_query 转换为 PDO->,但我不断收到 undefined variable 的错误$db

这是我的数据库连接页面代码:

$host = "localhost";
$user = "root";
$password = "";
$dbname = "XXXX";
global $db;
$db = new PDO("mysql:host=$host;dbname=$dbname;charset=UTF8", $user, $password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

编辑:我的注册函数有问题

<?php
###########################
#                         #
# Database Authentication #
#                         #
###########################

require('Database.php');
require('Bcrypt.php');
require('Session.php');

function register($username, $password, $email){
    if($username != null && $email != null && $password != null){
        /*
        $check = $database->prepare("SELECT * FROM users WHERE Username = '$username' OR Email = '$email'");
        $sql = $check->execute();
        if(count($check) > 0){
            echo "The username or email address you entered is already in use, please try another combination";
        }

                I currently have this commented out to test the INSERT query below
        */
        if(true){
            $salt = create_salt($username);
            $password = hash_pass($password, $salt);
            $query = $db->prepare("INSERT INTO users (Username, Password, Email) VALUES('$username', '$password', '$email')");
            $query->execute();
            return true;
        }
        else{
            echo "Something went wrong with inserting into table";
            return false;
        }
    }
    else{
        echo "Please fill in all of the information in order to register";
        return false;
    }
}

运行时我得到

Notice: Undefined variable: db in ...\Authentication.php on line 33

最佳答案

您需要将 global $db; 语句从它所在的位置移动到函数作用域中。

参见“示例 #1 使用全局here .

关于mysql - 使用 PDO 的 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943015/

相关文章:

PHP : could not find driver (PDO, MySql)

php - Apache 不加载 PDO SQLSRV 驱动程序错误 : 'could not find driver'

python - 在 Python 中连接到 MySQL 数据库时 UTF-8 不起作用

mysql - 选项卡和 ListView 中的 JSON 解析问题

Mysql:在UPDATE查询的两个条件下切换int字段的值

php - 从 Symfony 的表单中获取所有字段名称

java - 从 Android 应用程序向 MySQL 数据库提交数据

mysql - 避免在mysql中并发插入多个相同的id

php - pdo 类 vs pdostatment 类 - 初学者

php - CSS不想包含在文件中