1

I want to show the variable "points" which belongs to a certain username,.

This is a part of my login2.php file:

if(isset($_SESSION['username'])){
    $username=$_SESSION['username'];
    $points = $mysqli->query("SELECT points FROM account_information WHERE username = '".$username."'");

}

I dont know how to show the points now. I know that the outcome of $points is not the amount of points that belongs to a username. I actually want to know how to do this and what the outcome is of the $points. How can I show the actual result of the query I am running?(which would be the amount of points stored in my database So of course if you would run this query in mysql then the outcome will be :"Amount of points", but in this situation I dont know how to show the amount of points actually.

4

3 回答 3

3
while ($row = mysqli_fetch_assoc($points)) {
    echo $row['points'];
}

只需将结果放入一个名为 $row 的数组中,然后使用 $row['points'] 访问数组的各个部分。

于 2013-09-19T08:15:57.230 回答
3

在执行并获取 sql/results 之后,“points”值在里面。

获取行 http://www.php.net/manual/de/mysqli-result.fetch-row.php

$sql_result = $mysqli->query("SELECT points FROM account_information WHERE username = '".$username."'");

while ($data_row = mysqli_fetch_assoc($points)) {
    print 'Your score is: '.$data_row['points'];
}
于 2013-09-19T08:03:37.217 回答
1

OP 已经接受了答案,但他们都不是好 imoNDM 说的,看看那里的文档都写得很好

我认为混合 object 和 procedural style 也是非常糟糕的做法

此外,其他答案不关心 security$_SESSION['username']使用准备好的语句并重新选择用户名,因为 mysqli在这种情况下会验证您的用户名。

看看这个:

<?php
// Init the database connection
$db = new mysqli("example.com", "user", "password", "database");

// Look for errors or throw an exception
if ($db->connect_errno) {
    throw new Exception($db->connect_error, $db->connect_errno);
}

// Init prepared statement
$prep = $db->stmt_init();

// Prepared statement
$prep = $db->prepare("SELECT username, points FROM account_information WHERE username = ? AND username IS NOT NULL AND username != ''");

// See if statement is ok
if (!$prep) {
    throw new Exception($db->error);
}

// Put your variables into the query
$prep->bind_param('s', $_SESSION['username']);

// Fire the query!
$prep->execute();

// This is magic, it's awesome.. try it :-))
$prep->bind_result($username, $points);

// Get the results easily
while ($prep->fetch()) {
    echo "{$username} has {$points}<br>", PHP_EOL;
}

// This is like in our house, when we leave it, we close the door
$prep->close();
$db->close();

更新:

回答您的评论,这种风格更好,因为对象通常比程序功能更好。更好地编程,更好地阅读,更容易理解(从现实生活对象中抽象出来的对象)。 bind_param 验证您的输入。想象一下我;DROP TABLE account_information;--进入我的用户名会话。这是SQL 注入- 防止它们的唯一安全方法是prepare语句。或者想象一下拥有多个数据库连接。每个 mysqli 对象代表一个不同的连接。这不像程序风格那样清楚。此外,使用异常的错误报告更加灵活,因为它们可以是catched 和thrown。

如果您想了解更多关于他们的回报,只需阅读手册: http: //php.net/mysqli_query

mysqli_query / mysqli::query返回值:

失败时返回 FALSE。对于成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查询,mysqli_query() 将返回一个 mysqli_result 对象。对于其他成功的查询,mysqli_query() 将返回 TRUE。

于 2013-09-19T08:29:44.130 回答