Get data by id
To retrieve data by ID in PHP, you would typically use a database such as MySQL. Here’s a simple example of how you might achieve this:
<?php
$id = $_GET['id']; // Assuming ID is passed via GET request
// SELECT query
$query = "SELECT * FROM table_name WHERE id = $id";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// Output data for each row
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "0 results";
}
?>
In this example:
- Replace
"localhost","username","password", and"your_database"with your actual database connection details. - Adjust the SQL query according to your database schema.
- Ensure to properly handle input to avoid SQL injection vulnerabilities. In this example, I’ve used a prepared statement which helps prevent SQL injection when using dynamic data in SQL queries.
- The code retrieves the ID from a GET request parameter. Adjust this according to how you are receiving the ID in your application (e.g., POST request, form submission, etc.).
- Output or process the retrieved data as needed. In this example, I’ve simply echoed some data, but you can modify this to suit your application’s requirements.
