PHP,注意:未定义的变量,如何修复?

时间:2018-05-26 16:16:15

标签: php variables error-handling syntax-error

我在这里有注册表,我是PHP的虚拟(这个Android的Android应用程序),它工作,但我发现我可以使用相同的用户名和电子邮件注册,所以我添加了检查数据库相同用户名的功能并且防止这种情况,因为我是假的,我在尝试注册时遇到此错误 -

注意:未定义的变量:第27行的/storage/ssd1/448/5907448/public_html/Register.php中的con

警告:mysqli_prepare()要求参数1为mysqli,在第27行的/storage/ssd1/448/5907448/public_html/Register.php中给出为null

警告:mysqli_stmt_bind_param()要求参数1为mysqli_stmt,在第28行的/storage/ssd1/448/5907448/public_html/Register.php中给出为null

警告:mysqli_stmt_execute()要求参数1为mysqli_stmt,在第29行的/storage/ssd1/448/5907448/public_html/Register.php中给出null { “成功”:真}

我的PHP

<?php
$response = array();
if (!isset($_POST["username"], $_POST["email"], $_POST["password"])) {
        $response['success'] = false;
        $response['Error'] = "No needed data";
        echo json_encode($response);
        exit(0);
}

ob_start();
$con = mysqli_connect("host", "username", "password", "database");
ob_end_clean();

if (!$con) {
    $response['success'] = false;
    $response['Error'] = "Error Connecting" . PHP_EOL;
    $response['Error'] .= "Error Code: " . mysqli_connect_errno() . PHP_EOL;
    $response['Error'] .= "Error: " . mysqli_connect_error() . PHP_EOL;
    echo json_encode($response);
    exit(0);
}

     function registerUser() {
    $username = $_POST["username"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $statement = mysqli_prepare($con, "INSERT INTO user (username, email, password) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($statement, "sss", $username, $email, $password);
    mysqli_stmt_execute($statement);
     }

    function usernameAvailable() {
        global $con, $username;
        $statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?"); 
        mysqli_stmt_bind_param($statement, "s", $username);
        mysqli_stmt_execute($statement);
        mysqli_stmt_store_result($statement);
        $count = mysqli_stmt_num_rows($statement);
        mysqli_stmt_close($statement); 
        if ($count < 1){
            return true; 
        }else {
            return false; 
        }
    }
    $response["success"] = false;  
    if (usernameAvailable()){
        registerUser();
        $response["success"] = true;  
    }

    echo json_encode($response);
    ?>

PS - 连接数据已更改为默认值。

2 个答案:

答案 0 :(得分:0)

您引用了全局$ con并且它返回undefined。通过使用print_r或其他替代方法调试它,确保它具有值。由于它返回undefined没有正在运行的函数

虽然引用全局变量是不好的做法。我建议设置一个返回$ con变量或传递它的函数。

function returnCon(){
    $con = mysqli_connect("host", "username", "password", "database");

    return $con
}

然后您可以使用

$con = returnCon();

答案 1 :(得分:0)

将变量$con添加到需要访问数据库的函数的参数,即registerUser()和usernameAvailable()