我正在制作一个脚本来检查用户提供的凭据是否有效(用户存在)。我是一个 php 菜鸟,我不明白为什么我的脚本不起作用。
所以你能解释一下为什么如果我这样做它会起作用:
<?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();
?>
但如果我这样做它不会?
<?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'];
function check () {
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();
$mysqli->close();
?>
第一个版本的输出是 -> 行数:1(或 0,取决于输入)
但在第二个版本中,输出只是 -> check 调用。为什么这部分
$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();
用作函数时不执行