function getCategoryById($categoryId) { // create new PDO instance $pdo = new PDO('mysql:host=localhost;dbname=myDatabase', 'myUsername', 'myPassword'); // prepare SQL query to select category by ID $stmt = $pdo->prepare('SELECT * FROM categories WHERE id = :categoryId'); $stmt->bindParam(':categoryId', $categoryId); $stmt->execute(); // fetch category data as associative array $category = $stmt->fetch(PDO::FETCH_ASSOC); // close connection to database $pdo = null; return $category; } // fetch category with ID=1 $category = getCategoryById(1); echo $category['name']; // outputs the name of the category
function getCategoryById($categoryId) { // create new mysqli instance $mysqli = new mysqli('localhost', 'myUsername', 'myPassword', 'myDatabase'); // prepare SQL query to select category by ID $stmt = $mysqli->prepare('SELECT * FROM categories WHERE id = ?'); $stmt->bind_param('i', $categoryId); $stmt->execute(); // fetch category data as associative array $result = $stmt->get_result(); $category = $result->fetch_assoc(); // close connection to database $mysqli->close(); return $category; } // fetch category with ID=1 $category = getCategoryById(1); echo $category['name']; // outputs the name of the categoryIn both examples, the getCategoryById function takes a category ID as a parameter and retrieves the corresponding category data from the database. The function then returns the category data as an associative array. The package library used in these examples is either PDO or mysqli, depending on the example.