0
0
PHPprogramming~20 mins

Executing queries with query method in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Executing queries with query method
📖 Scenario: You are building a simple PHP script to fetch user data from a database. You will practice running SQL queries using the query method.
🎯 Goal: Create a PHP script that connects to a database, runs a SELECT query using the query method, and displays the user names.
📋 What You'll Learn
Create a mysqli connection object named $conn with host 'localhost', user 'root', password '', and database 'testdb'.
Create a SQL query string $sql to select all columns from the users table.
Use the query method on $conn with $sql to get the result in $result.
Loop through $result using fetch_assoc() and print each user's name.
Close the database connection at the end.
💡 Why This Matters
🌍 Real World
Fetching data from a database is a common task in web development to show dynamic content like user profiles or product lists.
💼 Career
Understanding how to execute queries and handle results is essential for backend developers working with PHP and MySQL databases.
Progress0 / 4 steps
1
Create the database connection
Create a mysqli connection object called $conn using new mysqli("localhost", "root", "", "testdb").
PHP
Need a hint?

Use the new mysqli(host, user, password, database) syntax to connect.

2
Write the SQL query string
Create a string variable called $sql and set it to "SELECT * FROM users".
PHP
Need a hint?

Assign the exact string "SELECT * FROM users" to $sql.

3
Run the query using the query method
Use the query method on $conn with $sql and store the result in $result.
PHP
Need a hint?

Use $conn->query($sql) to run the query.

4
Fetch and display user names
Use a while loop with $row = $result->fetch_assoc() to print each user's name with echo $row['name'] . "\n";. Then close the connection with $conn->close();.
PHP
Need a hint?

Use fetch_assoc() inside a while loop to get each row as an associative array.