使用PDO注册用户

时间:2012-12-23 11:24:29

标签: mysql pdo

我在处理寄存器时遇到问题

以下是该函数的代码:

<?php
include $_SERVER['DOCUMENT_ROOT']. "/config/config.php";
$conn = new PDO('mysql:host=' . $ip . ';dbname=' . $database, $username, $password);

function registerUser($username, $password, $passwordagain, $email, $mcname)
{
$validusername= "/^[a-z0-9]+$/";
$validpassword= "/^[A-Za-z0-9]+$/";
$validemail= "/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
$validmcname= "/^[A-Za-z0-9]+$/";
$error = 0;

if(strlen($username)<4 || strlen($username)>24)
{
$error = 1;
}
if(strlen($password)<6 || strlen($password)>24)
{
$error = 1;
}
if(strlen($mcname)<4 || strlen($mcname)>24)
{
$error = 1;
}
if(!preg_match($validusername, $username))
{
$error = 1;
}
if(!preg_match($validpassword, $password))
{
$error = 1;
}
if(!preg_match($validemail, $email))
{
$error = 1;
}
if(!preg_match($validmcname, $mcname))
{
$error = 1;
}
if($password != $passwordagain)
{
$error = 1;
}
$userexistquery = $conn->query('SELECT * FROM users WHERE username=' . $username);
$userexist = $userexistquery->fetch();
if(count($userexist) != 0)
{
$error=1;
echo "<div class='erroralert'>Username already exists!</div>";
}
$emailexistquery = $conn->query('SELECT * FROM users WHERE email=' . $email);
$emailexist = $emailexistquery->fetch();
if($emailexist != 0)
{
$error=1;
echo "<div class='erroralert'>E-mail already exists!</div>";
}
if($error != 1)
{
$encryptedpassword = hash('sha512', $password);
$registeruser = $conn->query("INSERT INTO users(username, password, email, mcname) VALUES ('$username', '$encryptedpassword', '$email', '$mcname')");
echo "<div class='successalert'>Succesfully registred</div>";
}
else
{
echo "<div class='erroralert'>An error occured during registration.</div>";
}
}
?>

给我的错误是:

  

注意:未定义的变量:第45行的C:\ xampp \ htdocs \ functions \ functions.php中的conn

     

致命错误:在第45行的C:\ xampp \ htdocs \ functions \ functions.php中调用非对象的成员函数query()

1 个答案:

答案 0 :(得分:2)

您在函数外部实例化变量$conn。你必须将它作为参数传递才能在里面使用它。