php准备的语句绑定会话


php prepared statement bind a session

如何设置SESSION并将其绑定到准备好的语句中,这样我就可以从mysqli获得一个结果,其中电子邮件等于我的SESSION['email']?

我有这个代码,我无法开始工作,所以它只会在我的会话电子邮件中得到结果:

public static function getById($email) {
// Initialize session array
$email = $_SESSION['email'];
// Build database query
$sql = "select * from users where email = ?";
// Open database connection
$database = new Database();
// Get instance of statement
$statement = $database->stmt_init();
// Prepare query
if ($statement->prepare($sql)) {
// Bind parameters
$statement->bind_param('s', $email);
// Execute statement
$statement->execute();
// Bind variable to prepared statement
$statement->bind_result($id, $first_name, $last_name, $username, $email,     $created, $active);
// Populate bind variables
$statement->fetch();
// Close statement
$statement->close();
}
// Close database connection
$database->close();
// Build new object
$object = new self;
$object->id = $id;
$object->first_name = $first_name;
$object->last_name = $last_name;
$object->username = $username;
$object->email = $email;
$object->created = $created;
$object->active = $active;
return $object;
}
$variable = "I am a variable";
function getVariable() {
    echo $variable;
}

Q( 为什么上面的脚本会出错?A( 作用域。。。

$_SESSION['email']不能在方法内部访问,您需要全局或定义它,或者将它作为参数传入。

function getById($email)
{
    echo $email;
}
session_start();
getById($_SESSION['email']);

绑定本质上只是在查询中的PHP变量和占位符之间设置一个指针/引用。就是这样。由于您绑定了$email,所以对$email的任何更改都不会对$_SESSION['email']产生影响,即使$email就是从这里来的。一旦任务完成,它们之间就没有代码链接。

你想要这个:

$statement->bind_param('s', $_SESSION['email']);

当您bind_result时也是类似的。$email$_SESSION之间没有链接,因此DB提取调用填充到$email中的任何内容都不会对会话变量产生影响。