doutun1875 2012-12-18 23:09
浏览 85
已采纳

使用PDO的未定义变量[重复]

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

I am new to PDO, and i am currently trying to convert all of my mysql_query's to PDO-> and I keep getting an error of an undefined variable $db

here is my code for the Database connection page:

$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);

Edit: my register function that is having problems

<?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;
    }
}

When running this i get

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

  • 写回答

3条回答 默认 最新

  • dongmengan8620 2012-12-18 23:15
    关注

    You need to move the global $db; statement from where it is into the function scope.

    See "Example #1 Using global" here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 vivo手机锁屏密码忘记了需要手机里的资料在百度里搜可以用ADB命令希望帮帮我
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出