php - PDO select results into variables
Get the solution ↓↓↓I'm just switching to PDO from mysql, and having some issues.
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. 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.
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.
For example:
ID_1, 25, 1st
Theres only 5 rows in the table, 1st to 5th.
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?
Answer
Solution:
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. Mind the iterator variable, $i, compared to your foreach loop.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function getclientoriginalname() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.