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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效