Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Get data by id in php

Get data by id

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
// Establish connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$database = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Get the ID from the request
$id = $_GET['id']; // Assuming the ID is passed through a GET request, adjust as needed

// Prepare SQL statement to retrieve data by ID
$sql = "SELECT * FROM your_table WHERE id = ?";

// Prepare statement
$stmt = $conn->prepare($sql);

// Bind parameters
$stmt->bind_param("i", $id);

// Execute statement
$stmt->execute();

// Get result
$result = $stmt->get_result();

// Check if any rows were returned
if ($result->num_rows > 0) {
// Fetch data
$row = $result->fetch_assoc();

// Output data (or use it as needed)
echo "ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
// Add more fields as needed
} else {
echo "No results found for ID: " . $id;
}

// Close statement and connection
$stmt->close();
$conn->close();
?>

In this example:

  1. Replace "localhost", "username", "password", and "your_database" with your actual database connection details.
  2. Adjust the SQL query according to your database schema.
  3. 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.
  4. 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.).
  5. 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.
Scroll to Top