绑定值错误

Error on bindValue

我已经浏览过 Internet,但无法找到并理解所提供的任何解决方案。

基本上,我创建了(或者说是从 Internet 上复制了一些脚本)并尝试使用这些脚本制作注册页面。我正在使用 PHP、Mysql 和 XAMPP。连接已经很好了。我在基本表单等上测试了一些数据输入。

但我的问题是,在我弄乱了脚本之后,我设法将数据插入 table (peekdoordb)...所有的散列和验证表单都有效...除了,表单即使数据错误或字段为空,也会继续将数据提交到数据库中。我又乱来之后,问题就来了。错误在“$stmt->bindValue(':name', $name);

我在浏览器上不断收到此错误;

Notice: Undefined variable: stmt in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194

Fatal error: Call to a member function bindValue() on a non-object in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194

registration.php(注册页面)包括2个文件,分别是connect.php和password.php,但我从来没有把这2个文件弄乱,因为在那之前,只能提交数据问题出在表格上,数据一直像我之前提到的那样插入到数据库中。但是现在主要的问题就是这个错误。

<?php

//register.php

/**
* Start the session.
*/
session_start();

//Include  password_compat library.

require 'lib/password.php';


//Include MySQL connection.

require 'connect.php';


//define variables and define to null.
$nameError = $telnoError = $usernameError = $passwordError ="";
$name = $telno = $username = $pass = "";


//Retrieve the field values from registration form.
$name = !empty($_POST ['name']) ? trim($_POST['name']) : null ;
$telno = !empty ($_POST ['telno']) ? trim($_POST['telno']) : null;
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}   

$formValid = true; // Boolean - Set to true b4 validating  

//If the POST var "register" exists ( the submit button), then I can
//assume that the user has submitted the registration form.
if(isset($_POST['register'])){


//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.

//Now, we need to check if the supplied username already exists.

//Construct the SQL statement and prepare it.

    if (empty($_POST["name"])) {
        $nameError = "Name is required";
    }else {
        $name = test_input($_POST["name"]);
// check name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameError = "Only letters and white space allowed";
        }
    }

    if (empty($_POST["telno"])) {
        $telnoError = "Tel number is required";
    } else {
        $telno = test_input($_POST["telno"]);
// check if e-mail address syntax is valid or not
        if (!preg_match("/^[a-zA-Z ]*$/",$telno)) {
            $telnoError = "Invalid tel no format";
        }
    }

    if (empty($_POST["username"])) {
        $usernameError = "username is required";
    } else {
        $username = test_input($_POST["username"]);
// check name only contains letters and email syntax
        if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
            $usernameError = "Only letters and email syntax required";
        }
    }


    if (empty($_POST["password"])) {
        $passwordError = "passworde is required";
    } else {
        $pass = test_input($_POST["password"]);
// check name only contains letters and email syntax
        if (!preg_match("/^[a-zA-Z ]*$/",$pass)) {
            $passwordError = "Only password letter syntax";
        }
    }


//*******************************************************************   



    $sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";

    $stmt = $pdo->prepare($sql);

//Bind the provided username to our prepared statement.
    $stmt->bindValue(':username', $username);


//Execute.
    $stmt->execute();

//Fetch the row.
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
    if($row['num'] > 0){
        die('That username already exists!');
    }

//Hash the password as we do NOT want to store our passwords in plain text.
    $passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
}



//If the signup process is successful.
elseif($formValid){


//******************************ppppp       

//Bind our variables.

    $stmt->bindValue(':name', $name);
    $stmt->bindValue(':telno', $telno);
    $stmt->bindValue(':username', $username);
    $stmt->bindValue(':password', $passwordHash);
    $stmt = $pdo->prepare($sql); 


//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
    $sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";




//Execute the statement and insert the new account.
    $result = $stmt->execute();





//What you do here is up to you!
    echo 'Thank you for registering with our website.';
}
else {
    die('something wrong!'); 
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Register</title>
    <style type="text/css">
        .lucida {
            font-family: "MS Serif", "New York", serif;
        }
        body form table {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>&nbsp;</h1>
    <h1>&nbsp;</h1>
    <h1 align="center">     Register</h1>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"  method="post">
        <div align="center">
            <table width="800" border="0">
                <tr>
                    <td width="404" class="lucida"><div align="right">Name :</div></td>
                    <td width="386"><input class="input" name="name" type="text" value="<?PHP print $name ; ?>">
                        <span class="error">* <?php echo $nameError;?></span></td>
                    </tr>
                    <tr>
                        <td class="lucida"><div align="right">Contact Number :</div></td>
                        <td><input class="input" name="telno" type="text" value="<?PHP print $telno ; ?>">
                            <span class="error">* <?php echo $telnoError;?></span></td>
                        </tr>
                        <tr>
                            <td class="lucida"><div align="right">Email (Username) :</div></td>
                            <td><input class="input" name="username" type="text" value="<?PHP print $username ; ?>">
                                <span class="error">* <?php echo $usernameError;?></span></td>
                            </tr>
                            <tr>
                                <td class="lucida"><div align="right">Password :</div></td>
                                <td><input class="input" name="password" type="text" value="">
                                    <span class="error">* <?php echo $passwordError;?></span></td>
                                </tr>
                                <tr>
                                    <td class="lucida"><div align="right"></div></td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td><div align="right"></div></td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td><div align="right"></div></td>
                                    <td>&nbsp;</td>
                                </tr>
                            </table>
                            <input type="submit" name="register" value="Register">
                            <br>
                        </div>
                    </button>
                </form>
            </body>
            </html>

试试这个 -

//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";

$stmt = $pdo->prepare($sql); 

$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);


//Execute the statement and insert the new account.
$stmt->execute();

您的语句 prepare 之前有 bindValue,所以您收到此错误。可以 prepare 你的 $sql 变量下面的语句然后绑定你的值。这对我有用。

更新的答案

<?php
//register.php

/**
 * Start the session.
 */
session_start();

//Include  password_compat library.
require 'lib/password.php';
//Include MySQL connection.

require 'connect.php';


//define variables and define to null.
$nameError = $telnoError = $usernameError = $passwordError = "";
$name = $telno = $username = $pass = "";


//Retrieve the field values from registration form.
$name = !empty($_POST ['name']) ? trim($_POST['name']) : null;
$telno = !empty($_POST ['telno']) ? trim($_POST['telno']) : null;
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

$formValid = true; // Boolean - Set to true b4 validating  
//If the POST var "register" exists ( the submit button), then I can
//assume that the user has submitted the registration form.
if (isset($_POST['register'])) {


//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.

    if (empty($_POST["name"])) {
        $nameError = "Name is required";
        $formValid = false;
    } else {
        $name = test_input($_POST["name"]);
// check name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
            $nameError = "Only letters and white space allowed";
            $formValid = false;
        }
    }

    if (empty($_POST["telno"])) {
        $telnoError = "Tel number is required";
        $formValid = false;
    } else {
        $telno = test_input($_POST["telno"]);
// check if e-mail address syntax is valid or not
        if (!preg_match("/^[a-zA-Z ]*$/", $telno)) {
            $telnoError = "Invalid tel no format";
            $formValid = false;
        }
    }

    if (empty($_POST["username"])) {
        $usernameError = "username is required";
        $formValid = false;
    } else {
        $username = test_input($_POST["username"]);
// check name only contains letters and email syntax
        if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
            $usernameError = "Only letters and email syntax required";
            $formValid = false;
        }
    }


    if (empty($_POST["password"])) {
        $passwordError = "passworde is required";
        $formValid = false;
    } else {
        $pass = test_input($_POST["password"]);
// check name only contains letters and email syntax
        if (!preg_match("/^[a-zA-Z ]*$/", $pass)) {
            $passwordError = "Only password letter syntax";
            $formValid = false;
        }
    }


//*******************************************************************   



    $sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";

    $stmt = $pdo->prepare($sql);

//Bind the provided username to our prepared statement.
    $stmt->bindValue(':username', $username);


//Execute.
    $stmt->execute();

//Fetch the row.
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
    if ($row['num'] > 0) {
        $usernameError = 'That username already exists!';
        $formValid = false;
    }

//Hash the password as we do NOT want to store our passwords in plain text.
    $passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
    //$passwordHash = $pass;

    if ($formValid) {
//******************************ppppp       
//Bind our variables.
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
        $sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
        $stmt = $pdo->prepare($sql);

        $stmt->bindValue(':name', $name);
        $stmt->bindValue(':telno', $telno);
        $stmt->bindValue(':username', $username);
        $stmt->bindValue(':password', $passwordHash);





//Execute the statement and insert the new account.
        $result = $stmt->execute();





//What you do here is up to you!
        echo 'Thank you for registering with our website.';
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Register</title>
        <style type="text/css">
            .lucida {
                font-family: "MS Serif", "New York", serif;
            }
            body form table {
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <h1>&nbsp;</h1>
        <h1>&nbsp;</h1>
        <h1 align="center">     Register</h1>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"  method="post">
            <div align="center">
                <table width="800" border="0">
                    <tr>
                        <td width="404" class="lucida"><div align="right">Name :</div></td>
                        <td width="386"><input class="input" name="name" type="text" value="<?PHP print $name; ?>">
                            <span class="error">* <?php echo $nameError; ?></span></td>
                    </tr>
                    <tr>
                        <td class="lucida"><div align="right">Contact Number :</div></td>
                        <td><input class="input" name="telno" type="text" value="<?PHP print $telno; ?>">
                            <span class="error">* <?php echo $telnoError; ?></span></td>
                    </tr>
                    <tr>
                        <td class="lucida"><div align="right">Email (Username) :</div></td>
                        <td><input class="input" name="username" type="text" value="<?PHP print $username; ?>">
                            <span class="error">* <?php echo $usernameError; ?></span></td>
                    </tr>
                    <tr>
                        <td class="lucida"><div align="right">Password :</div></td>
                        <td><input class="input" name="password" type="text" value="">
                            <span class="error">* <?php echo $passwordError; ?></span></td>
                    </tr>
                    <tr>
                        <td class="lucida"><div align="right"></div></td>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td><div align="right"></div></td>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td><div align="right"></div></td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
                <input type="submit" name="register" value="Register">
                <br>
            </div>
        </button>
    </form>
</body>
</html>

the form keeps submitting data into the DB even when data is wrong or the field is empty

您在错误的地方检查 $formValid。您的情况可以概括如下:

$formValid = true;
if (isset($_POST['register'])) {

} else if ($formValid) {

} else { ...

如上所述,如果未设置 $_POST['register'](例如,在加载注册表时),您的代码将执行第二个 if 语句中的任何内容。您的条件结构应修改为在第一个条件内包含表单有效性检查:

$formValid = true;
if (isset($_POST['register'])) {
    // validation stuff goes here
    if ($formValid) {
        //database insert goes here
    }
    else {
        //invalid data. Tell the user
    }
}

此外,作为一项规则,您应该假设来自用户的任何数据都是无效的,除非另有证明,即 $formValid 最初应该是 false

Notice: Undefined variable: stmt in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 19 Fatal error: Call to a member function bindValue() on a non-object in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194

您正在尝试使用尚未在 else if($formValid) 范围内定义的变量 $stmt$sql 也是如此。任何变量都必须在使用前设置。顺序应该是:

$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";

$stmt = $pdo->prepare($sql); 

$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);