这是代码:
$connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
function send($username="", $password="") {
$connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}
$connect->close();
注意:未定义的变量:在第44行的C:\ xampp \ htdocs \ playground01 \ build \ components \ includes \ root.php中连接
致命错误:在第44行的C:\ xampp \ htdocs \ _ playground01 \ build \ components \ includes \ root.php中调用null上的成员函数query()
哪里有问题?
答案 0 :(得分:1)
这是因为PHP中的variable scope。 $connect
在send
之外定义,因此无法访问。将其作为参数传递,在函数中定义它,或使用global
。
A)
function send($username="", $password="", $connect) {
$connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}
$connect->close();
然后在send
来电中传递$connect
。
b)中
function send($username="", $password="", $connect) {
$connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
$connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}
$connect->close();
c)中
function send($username="", $password="") {
global $connect;
$connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}
$connect->close();
此外,您应该将parameterized queries与prepared statements一起使用。
第三点,密码不应以明文http://security.blogoverflow.com/2011/11/why-passwords-should-be-hashed/存储。
答案 1 :(得分:0)
如果你想这样做,你必须在函数中声明你要使用的全局变量:
function send($username="", $password="") {
global $connect;
$connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}
甚至更好,使连接成为函数参数:
function send($connect, $username="", $password="") {
$connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}