简体   繁体   English

PDO将结果选择为变量

[英]PDO select results into variables

I'm just switching to PDO from mysql, and having some issues. 我只是从mysql切换到PDO,遇到了一些问题。

I'm trying to do something that was immensely simple with mysql, all I want to do it save the result of my query into variables. 我正在尝试使用mysql做非常简单的事情,我想做的就是将查询结果保存到变量中。 I've trawled the interweb all day and every example is echoing or printing the results, whereas i need them in variables so I can then use them in the rest of my application. 我整天拖曳了Interweb,每个示例都在回显或打印结果,而我需要在变量中使用它们,以便可以在应用程序的其余部分中使用它们。

I have a simple db table for storing points for where someone finishes. 我有一个简单的数据库表,用于存储某人完成任务的点。 An id, the points to be allocated and the position of those points. 一个id,要分配的点以及这些点的位置。

For example: 例如:

ID_1, 25, 1st ID_1,25,第一

Theres only 5 rows in the table, 1st to 5th. 表中只有5行,第1至第5行。

I want to have the points into variables like: 我想将这些点放入变量中,例如:

$point_1 = 25
$point_2 = 20
$point_3 = 18
$point_4 = 15
$point_5 = 10

This is the code im using: 这是我使用的代码:

$dbh = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);

$sql = "SELECT * FROM points";
$stmt = $dbh->prepare($sql);
$stmt->execute();
// here you go:
$points = $stmt->fetchAll();

foreach ($points as $row) {

 print $row["point_position"] . "-" . $row["point_value"] ."<br/>";

}

But i want to get the values into variables? 但是我想把值变成变量? not print or echo them? 无法打印或回显它们?

If I understand your issue correctly this might help: 如果我正确理解您的问题,这可能会有所帮助:

$result = array();

foreach ( $points as $i => $row ) {
    $result[$i] = $row;
}

Now each row from the query is at their unique position in the $result array. 现在,查询的每一行都在$ result数组中的唯一位置。 Mind the iterator variable, $i, compared to your foreach loop. 与foreach循环相比,请注意迭代器变量$ i。

尝试将查询结果关联到关联数组

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

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