将查询结果转换为PHP变量

时间:2011-12-16 23:21:02

标签: php

以下查询位于$submissionid只有一个值的页面上。因此,字段points只有一个值。

如何将points从下面的查询转换为常规PHP变量?

  $sqlStra = "SELECT points, submissionid
               FROM submission 
              WHERE submissionid = '$submissionid'";

编辑:这是从MySQL数据库中提取的。

编辑II:我希望points等于整个页面上的变量,而不仅仅是在while循环中。

4 个答案:

答案 0 :(得分:1)

通过这种方式,您可以阅读查询返回的所有点。

while ($row = mysql_fetch_array($sqlStra, MYSQL_ASSOC)) {
    $points = $row["points"]);
}

答案 1 :(得分:0)

我会使用ORM库(我使用与Kohana捆绑的库)来消除SQL注入的可能性。但是,假设已经建立了数据库连接,则此代码将执行您要查找的内容。

$resource = mysql_query("SELECT points, submissionid FROM submission WHERE submissionid = '$submissionid'");
$result = mysql_fetch_assoc($resource);
echo $result["points"];

如果您没有建立MySQL数据库连接,请查看mysql_connect

答案 2 :(得分:0)

好吧,你需要从该查询中获取资源,然后将其提供给mysql_fetch_assoc,如下所示:

$res = mysql_query($sqlStra);

// If you **Know for sure** you'll only have one row:
$row = mysql_fetch_assoc($res);
$points = $row['points'];

//Otherwise, you're going to need to loop.
$array_of_all_points = array();

while ($row = mysql_fetch_assoc($res)) {
    // $row['points'] now has what you want. You can assign it normally, or can use
    // extract($row) to turn it into $points, which I would advise against personally.
    $points = $row['points'];
    $array_of_all_points[$row['submissionid']] = $row['points'];
}

echo $points; // This will be the last $row['points'] that was executed.
echo $array_of_all_points['thatsubmissionid']; // Will output the points for the given session id. 

此外,该查询不安全(如果$ submitid来自用户输入,它易受SQL注入攻击),您应该使用ORM库作为iloveitaly提及。 (我使用Zend DB,虽然它本身并不是技术上的ORM)

编辑:

正如评论所指出的,这取决于你是否真正使用Mysql。如果不是,您可以使用PDO library进行查询。

答案 3 :(得分:0)

$sqlStra = "SELECT points FROM submission WHERE submissionid = ?"; 

$statement = $connection->prepare($sqlStra);
$statement->bind_param('i', $submissionid);
$statement->bind_result($points);
$statement->execute();
$statement->fetch(); // this will create / populate $points