-1

我正在制作一个脚本来检查用户提供的凭据是否有效(用户存在)。我是一个 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();

用作函数时不执行

4

2 回答 2

4

因为,该$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);
于 2013-10-27T20:36:58.273 回答
0

因为您没有传递给函数check ()变量$email$password. 如果在函数中不使用 global 关键字,则该变量将仅在函数范围之外可见。

如果需要,可以使用 global 关键字在函数中使用全局范围内的变量:

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();
}

在此处查看有关变量范围和全局关键字的更多信息。

于 2013-10-27T20:38:15.873 回答