// Connect to the database $pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password'); // Query to retrieve user with ID 123 $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute(['id' => 123]); // Fetch the user data as an associative array $user = $stmt->fetch(PDO::FETCH_ASSOC); // Print the user's name echo $user['name'];
// Connect to the database $conn = mysqli_connect('localhost', 'username', 'password', 'my_database'); // Query to retrieve user with ID 456 $result = mysqli_query($conn, 'SELECT * FROM users WHERE id = 456'); // Fetch the user data as an object $user = mysqli_fetch_object($result); // Print the user's email address echo $user->email;In this example, we use the mysqli extension to connect to a MySQL database and retrieve the user with an ID of 456 from the "users" table. We then store the user data in an object and print their email address to the screen. Package/Library: MySQLi Overall, the "get_by_id" method is a useful function in PHP for retrieving specific user data from a database. It can be used with different PHP database extensions to connect and query databases.