我已经能够从MySQL数据库中查询数据并将数组放入变量$ results中,但是我无法将数组的一部分放入,如$ result变量中的密码或regtime分成变量。我做错了什么?
这是我的数据库类中的select函数,我使用$ query的参数查询数据库中的数据。这适用于我的帖子页面,所以我不认为这是问题。
// Select Function
public function select($query){
$result = $this->connection->query($query);
while ( $obj = $result->fetch_object()){
$results[] = $obj;
}
return $results;
}

这是我的查询类中的登录函数,我将提交的用户名放入查询中,然后将其传递给上面的select函数,用该用户名拉取结果,返回登录函数并存储在$ results变量。然后它检查变量是否为空,如果它是杀死脚本,这就是我得到的全部工作:
1)yay!!!!
2)print_r()
显示的内容是:
Array ( [0] => stdClass Object ( [ID] => 1 [username] => dillon [fname] => Dillon [lname] => Erhardt [email] => dillon@erhardt.co.uk [password] => dilandsas [regtime] => 1453685794 ) )
function login($redirect) {
global $db;
if(!empty($_POST)) {
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
$query = "
SELECT * FROM users
WHERE username = '$username'
";
$results = $db->select($query);
//Kill the script if the submitted username doesn't exit
if (empty($results)) {
die('Sorry, that username does not exist!');
}
echo "yay";
print_r($results);
//The registration date of the stored matching user
$storeg = $results['regtime'];
//The hashed password of the stored matching user
$stopass = $results['password'];

问题在于,当我尝试使用$results['password'];
或$results['regtime'];
从密码或regtime结果存储我的$ storeg和$ stopass变量中的vaule时,我会收到这些通知
Notice: Undefined index: regtime in /Applications/MAMP/htdocs/Test/CMS-v2/includes/class-query.php on line 55
Notice: Undefined index: password in /Applications/MAMP/htdocs/Test/CMS-v2/includes/class-query.php on line 58
Invalid Login
如何将数组中的密码和regtime值存储到$ results变量?
答案 0 :(得分:1)
请尝试以下代码。
function login($redirect) {
global $db;
if(!empty($_POST)) {
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
$query = "
SELECT * FROM users
WHERE username = '$username'
";
$results = $db->select($query);
//Kill the script if the submitted username doesn't exit
if (empty($results)) {
die('Sorry, that username does not exist!');
}
echo "yay";
print_r($results);
//The registration date of the stored matching user
$storeg = isset($results[0]->regtime) ? $results[0]->regtime : "";
//The hashed password of the stored matching user
$stopass = isset($results[0]->password) ? $results[0]->password : "";
答案 1 :(得分:0)
在您的选择中,您从结果集中获取对象并将其添加到数组(result
)。
因此,您需要从结果数组中获取对象并引用该属性:
$storeg = $results[0]->regtime;
如果$result
包含数据库中的一行且恰好一行,这显然只会起作用。所有其他情况(无行,三行)都会因错误处理而导致错误。