PHP-如果通过函数调用,则查询不会执行
我正在制作一个脚本,检查用户提供的凭据是否有效(用户存在)。我是一个PHPNoob,我不明白为什么我的脚本不能工作 那么,你能解释一下为什么我这么做会奏效吗:PHP-如果通过函数调用,则查询不会执行,php,mysql,function,Php,Mysql,Function,我正在制作一个脚本,检查用户提供的凭据是否有效(用户存在)。我是一个PHPNoob,我不明白为什么我的脚本不能工作 那么,你能解释一下为什么我这么做会奏效吗: <?php // include database constants include_once("../config/config.php"); // create db connection $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS
<?php
// include database constants
include_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $mysqli -> prepare("SELECT * FROM mytable WHERE email=? AND password=?");
$stmt -> bind_param("ss", $email, $password);
$stmt -> execute();
$stmt-> store_result();
printf(" Number of rows: %d.\n", $stmt->num_rows);
$stmt -> close();
$mysqli->close();
?>
作为函数使用时不会执行,因为
$mysqli
变量在check()
中不可访问,这就是原因
这就是它的工作原理-只需将参数传递给函数:
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
function check (MySQLi $mysqli, $email, $password) {
// Your stuff
}
check($mysqli, $email, $password);
function check () {
global $email; // from gloabl scope
global $password; // from global scope
global $mysqli; // from global scope
printf("check called\n"); //debug
$stmt = $mysqli -> prepare("SELECT * FROM mytable WHERE email=? AND password=?");
$stmt -> bind_param("ss", $email, $password);
$stmt -> execute();
$stmt -> store_result();
printf(" Number of rows: %d.\n", $stmt->num_rows);
$stmt -> close();
}
因为您没有传递到函数
check()
变量$email
和$password
。如果在函数中不使用全局关键字,则变量将仅在函数范围外可见
如果需要,可以使用global关键字在函数的全局范围内使用它变量:
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
function check (MySQLi $mysqli, $email, $password) {
// Your stuff
}
check($mysqli, $email, $password);
function check () {
global $email; // from gloabl scope
global $password; // from global scope
global $mysqli; // from global scope
printf("check called\n"); //debug
$stmt = $mysqli -> prepare("SELECT * FROM mytable WHERE email=? AND password=?");
$stmt -> bind_param("ss", $email, $password);
$stmt -> execute();
$stmt -> store_result();
printf(" Number of rows: %d.\n", $stmt->num_rows);
$stmt -> close();
}
请参阅有关变量范围和全局关键字的更多信息。db变量不是全局变量,它需要是一个参数Jari,Cristian Bitoi谢谢你们的回答。我掷硬币决定我接受的答案,因为我认为它们同样好。我认为它们是全球性的。我不知道它们必须明确声明为全局。谢谢