无法使用PHP插入MySQL表

时间:2010-08-08 02:23:10

标签: php mysql database

无法在表格中插入新记录。有人在乎帮忙吗?

<?php include('config.php'); ?>
<?php 

if(!empty($_POST['forename']) && !empty($_POST['surname']) && !empty($_POST['email']) && !empty($_POST['emailconfirm']) && !empty($_POST['password'])) {
    if($_POST['email'] == $_POST['emailconfirm']) {
        $forename = mysql_real_escape_string($_POST['forename']);
        $surname = mysql_real_escape_string($_POST['surname']);
        $email = mysql_real_escape_string($_POST['email']);
        $password = md5(mysql_real_escape_string($_POST['password']));
        register();
    }
    else { $errormessage = "Emails do not match"; }
}
else { $errormessage = "Not all fields filled"; }

function register() {
$check = mysql_query("SELECT * FROM Users WHERE EmailAddress = '".$email."'");
    if (mysql_num_rows($check) == 1) {
        $errormessage = "Account already exists with the email address provided";
    }
    else {
        $register = mysql_query("INSERT INTO Users (EmailAddress, Password, Forename, Surname) VALUES('".$email."', '".$password."', '".$forename."', '".$surname."')");
        $errormessage = "Account Added";
    }
}
?>

我认为问题出在MySQL查询语句中?

2 个答案:

答案 0 :(得分:1)

register函数中的变量超出范围。需要将它们全球化。

function register() {
    global $email, $password, $forename, $surname, $errormessage;

    $check = mysql_query("SELECT * FROM Users WHERE EmailAddress = '".$email."'");
    if (mysql_num_rows($check) == 1) {
        $errormessage = "Account already exists with the email address provided";
    }
    else {
        $register = mysql_query("INSERT INTO Users (EmailAddress, Password, Forename, Surname) VALUES('".$email."', '".$password."', '".$forename."', '".$surname."')");
        $errormessage = "Account Added";
    }
}

答案 1 :(得分:0)

没有params传递给函数register() ??在此文件中,您希望使用register()将记录添加到sql。但是register()怎么能知道$mail变量应该使用什么值呢? 您可以通过以下方式在global中使用register()

global  $email, $password, $forename, $surname, $errormessage;

或者您可以将register()重写为

function register($email, $password, $forename, $surname, $errormessage){....}

并将参数传递给register($email, $password, $forename, $surname, $errormessage)