0
0
PHPprogramming~5 mins

Executing queries with query method in PHP

Choose your learning style9 modes available
Introduction

The query method lets you send commands to a database to get or change data easily.

When you want to get data from a database table.
When you need to add new data to a database.
When you want to update existing data in a database.
When you want to delete data from a database.
When you want to run simple SQL commands quickly.
Syntax
PHP
$result = $connection->query("SQL statement");

The query method runs the SQL command you give it.

It returns a result object for SELECT queries or TRUE/FALSE for others.

Examples
This gets all rows from the users table.
PHP
$result = $conn->query("SELECT * FROM users");
This adds a new user named Anna who is 25 years old.
PHP
$result = $conn->query("INSERT INTO users (name, age) VALUES ('Anna', 25)");
This changes Anna's age to 26.
PHP
$result = $conn->query("UPDATE users SET age = 26 WHERE name = 'Anna'");
This removes the user named Anna from the table.
PHP
$result = $conn->query("DELETE FROM users WHERE name = 'Anna'");
Sample Program

This program connects to a database, runs a SELECT query to get all users, and prints their id and name. It shows how to use the query method and handle results.

PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

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

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

// Run a SELECT query
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . " - Name: " . $row["name"] . "\n";
    }
} else {
    echo "0 results\n";
}

$conn->close();
?>
OutputSuccess
Important Notes

Always check if the query worked by testing the result.

For SELECT queries, the result is an object you can loop through.

For other queries like INSERT or UPDATE, the result is TRUE on success or FALSE on failure.

Summary

The query method runs SQL commands on the database.

Use it to get, add, update, or delete data.

Check the result to know if the query worked and to get data back.