繁体   English   中英

将查询结果转换为PHP变量

[英]Turning a result from a query into a PHP variable

下面的查询在页面上,其中$submissionid只有一个值。 因此,场points仅具有一个值。

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

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

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

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

这样,您可以读取查询返回的所有点。

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

我将使用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

好吧,您需要从该查询中获取资源,然后将其提供给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. 

此外,该查询也不安全(如果$ submissionid来自用户输入,则容易受到SQL注入的攻击),您应该使用iloveitaly提到的ORM库。 (我使用Zend DB ,尽管从技术上讲它并不是ORM本身)

编辑:

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

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM