bg2982
bg2982

Reputation: 69

Allow user to select specific row of sql select results?

Not sure if this is even possible so sorry if this is a stupid question. I have a sql select query that I will post below. It displays 5 fields into a table from my orders database table. Is there any way that a user can click on one of the rows and then that would take them to a new page showing only that rows results? Is it somehow possible to store the select query results into a session for me to call on the next page? I would like them to be able to print invoices this way. Here is the select sql code.

$sql = "SELECT id, login_id, companyname, address, cost FROM orders WHERE   `login_id` = '$_SESSION[login]'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>id</th><th>login_id</th><th>companyname</th>tr><th>address</th><th>cost</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["id"]."</td><td>".$row["login_id"]."</td><td>".$row["companyname"]."</td><td>".$row["address"]."</td><td>".$row["cost"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();

Upvotes: 0

Views: 270

Answers (2)

Praxis Ashelin
Praxis Ashelin

Reputation: 5217

Expanding on i486's answer, here is how you can achieve it in more detail:

Since you already have the $row["id"], you can use this to generate a link:

echo "<a href='newpage.php?id=".$row["id"]."'>Click here</a>";

Now in newpage.php:

// You can access parameters in the url using GET
$id = $_GET["id"];

// Now you can build a new SQL query using this $id, and echo the results table

Do look up the following things:

  • REST: This explains how GET and POST works
  • Prepared SQL statements: This will prevent SQL injection, and is needed when you are working with GET or POST values in an SQL query (otherwhise malicious users can destroy your database!)

Upvotes: 0

i486
i486

Reputation: 6563

Simply save the value of first column (ID). Then use it for new query which selects only this row.

Upvotes: 1

Related Questions