'Output a Single Row from a MySQL Database in a Simple PHP Site without CSS
I have a small database for a school project that is built like:
Seatnumber | Name | Age | Address
and has around 30 Lines...
I want a blank site with an input field where I can enter one of the 4 values and get as an output the whole row where one value is correct.
So I mean when I had the table like this:
| Seatnumber | Name | Age | Address |
|---|---|---|---|
| 1 | Smith | 24 | Berlin |
| 2 | Mueller | 25 | Berlin |
| 3 | Peter | 24 | Bonn |
I want to enter in the field the number 24 (Probably I need a dropdown field in front of the input field in which category I want to search the value?) and want to output the complete row 1 & 3 because both had the age "24"
Currently I got this that can output the whole table
$sql = "SELECT * FROM Sitzplan";
foreach ($pdo->query($sql) as $row) {
echo "Sitzplatz: ".$row['Sitznummer'].". ".$row['Name']." ".$row['Alter']."<br />";
echo "Wohnort: ".$row['Wohnort']."<br /><br />";
}
I Hope you guys can help me with this because I only know Lua and want to have it on a website because of our stupid school rules for not using external programs.
And already many Thanks for the Help! I hope my English is not so bad that nobody can read it. And the last thing I created the table simply with PHPmyAdmin if this is important
Solution 1:[1]
Use a form and get their values using $_POST
<form method="post">
<select name="field">
<option value="age">Age</option>
<option value="name">Name</option>
</select>
<input type="text" name="value" placeholder="Value..." />
<button>Submit</button>
</form>
On user input, make request a little different :
if ($_POST) {
$field = $_POST['field'];
$value = $_POST['value'];
$req = "SELECT * FROM Sitzplan WHERE $field = ?";
} else {
$req = "SELECT * FROM Sitzplan";
}
$sth = $pdo->prepare($req);
$sth->execute([$value ?? null]); // prevents error if $value is undefined (on no user input)
$results = $sth->fetchAll();
Note that I am preparing the request before executing it
Then simply loop $results like you did
foreach ($results as $row) {
echo "Sitzplatz: ".$row['Sitznummer'].". ".$row['Name']." ".$row['Alter']."<br />";
echo "Wohnort: ".$row['Wohnort']."<br /><br />";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ownagin |
