0

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

这是该函数的代码:

<?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()

4

1 回答 1

2

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

于 2012-12-23T11:27:13.033 回答