function getProductById($product_id) { // connect to database $conn = mysqli_connect("localhost", "username", "password", "mydb"); // prepare query $query = "SELECT * FROM products WHERE id = $product_id"; // execute query $result = mysqli_query($conn, $query); // fetch data $product = mysqli_fetch_assoc($result); // close connection mysqli_close($conn); // return product return $product; }
class Product { private $id; private $name; private $price; private $description; // constructor public function __construct($id) { // retrieve product from database $product = $this->getProductById($id); // set properties $this->id = $product['id']; $this->name = $product['name']; $this->price = $product['price']; $this->description = $product['description']; } // get product by ID private function getProductById($product_id) { // connect to database $conn = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password'); // prepare query $query = "SELECT * FROM products WHERE id = $product_id"; // execute query $result = $conn->query($query); // fetch data $product = $result->fetch(PDO::FETCH_ASSOC); // close connection $conn = null; // return product return $product; } // getters public function getId() { return $this->id; } public function getName() { return $this->name; } public function getPrice() { return $this->price; } public function getDescription() { return $this->description; } }This code example uses the PDO extension to connect to a MySQL database and retrieve a product with a specific ID. It defines a Product class and uses the constructor to retrieve product information from the database and set the object properties. It also includes getter methods for accessing information about the product. Package Library: PDO.