使用PDO创建会话

时间:2014-10-27 14:56:52

标签: php mysql sql pdo phpmyadmin

我在登录表单的会话页面中使用了一些代码,但它使用mysql_*函数:

<?php
$connection = mysql_connect("localhost", "root", "password");
$db = mysql_select_db("database", $connection);

session_start();// Starting Session
$user_check=$_SESSION['login_user'];

$ses_sql=mysql_query("select * from login where email='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['email'];
$user_id =$row['id'];
$user_passwords = $row['password'];


if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: login_form.html'); // Redirecting To Home Page
}
?>

我正在尝试将其更改为PDO。到目前为止,我已经做了这些修改,但我不确定它们是否正确:

<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$dbhost     = "localhost";
$dbname     = "databse";
$dbuser     = "root";
$dbpass     = "password";

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);

session_start();
$user_check=$_SESSION['login_user'];

$result = $conn->prepare("SELECT * FROM login WHERE email= :$user_check");
$row = $result->fetch(PDO::FETCH_ASSOC)

$login_session =$row['email'];
$user_id =$row['id'];
$user_passwords = $row['password'];

if(!isset($login_session)){
$conn = null; // Closing Connection
header('Location: login_form.html'); // Redirecting To Home Page
}
?>

任何人都可以告诉我,如果我这样做了吗?

3 个答案:

答案 0 :(得分:0)

我建议您更改下面的代码。您应该执行$result

$result = $conn->prepare("SELECT * FROM login WHERE email = :user_check");
$result->bindValue(':user_check', $user_check);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);

答案 1 :(得分:0)

看起来不错,除了:

$result = $conn->prepare("SELECT * FROM login WHERE email= :$user_check");
$row = $result->fetch(PDO::FETCH_ASSOC);

当你做一个prepare()时,你必须传递execute()中的参数(或使用bindValue(),如其他人所示,但这种方式更清晰,IMO)

$result = $conn->prepare("SELECT * FROM login WHERE email= :usercheck");
$result->execute(array(":usercheck"=>$user_check));
$row = $result->fetch(PDO::FETCH_ASSOC);

别忘了用分号;)

答案 2 :(得分:0)

在抓取之前不要忘记execute()并且占位符不带美元符号:

$result = $conn->prepare("SELECT * FROM login WHERE email= :user_check");
$result->execute(array(':user_check'=>$user_check));
$row = $result->fetch(PDO::FETCH_ASSOC);