我有一篇早先的帖子here 但这些答案都没有奏效。所以这是我的全部类代码:
<?php
session_start();
class Mysql {
private $conn;
function __construct() {
$this->conn = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***') or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// User exist
$stmt->bindColumn('First Name', $firstName);
$_SESSION["FirstName"] = $firstName;
die($_SESSION["FirstName"]);
return true;
$stmt->close();
}
else {
// User doesn't exist
//die("failure");
return false;
$stmt->close();
}
}
}
?>
我尝试过fetch,我尝试过bind_result等,但没有一个在die语句中打印正确的值。现在,当我在会话中存储用户名并尝试打印时,工作。代码有什么问题?
答案 0 :(得分:1)
我查看了你的代码,并在我自己的服务器上创建了一个可用的版本。如果您有任何疑问,请随时提出。
class Mysql
{
private $conn;
public $error;
public $username;
function __construct()
{
try {
$this->conn = new PDO( 'mysql:host=localhost;dbname=****', 'root', '****' );
$this->conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
}
catch ( Exception $e ) {
$this->error = $e->getMessage();
}
}
function verify_Username_and_Pass( $un, $pwd )
{
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare( $query );
if( !$stmt ) {
$this->error = $this->conn->errorInfo();
return false;
}
$stmt->bindParam( ':un', $un );
$stmt->bindParam( ':pwd', $pwd );
$stmt->execute();
if ( $stmt->rowCount() > 0 ) {
// User exist
$this->username = $stmt->fetchColumn();
return true;
}
else {
// User doesn't exist
return false;
}
}
}
session_start();
$db = new Mysql();
if( !$db->error ) {
if( $db->verify_Username_and_Pass ( 'user', 'test' )) {
$_SESSION["FirstName"] = $db->username;
}
else
echo 'Unknown user';
}
var_dump( $db );
脚本将输出:
Unknown user
object(Mysql)#1 (3) {
["conn":"Mysql":private]=> object(PDO)#2 (0) { }
["error"]=> array(3)
{ [0]=> string(5) "42S02"
[1]=> int(1146)
[2]=> string(39) "Table 'xxxx.Conference' doesn't exist" }
["username"]=> NULL }
答案 1 :(得分:1)
您没有在代码段中调用代码。什么是通话程序?
您不会仅Conference.First Name
检索Conference.Username
,因此您应该收到警告,除非您没有显示错误。你可能想要
"SELECT * FROM Conference...."
或
"SELECT FirstName From Conference WHERE Username = :un AND Password = :pwd";
可能是Conference.FirstName
。
die();
对调试不是很有用。试试var_dump($_SESSION["FirstName"]); die();