Tags
Asked 3 years ago
10 Aug 2021
Views 230
Pearline

Pearline posted

How do I create a query in PHP ?

How do I create a query in PHP ?
andy

andy
answered May 1 '23 00:00

programmer can create a query using the MySQLi or PDO extension , which provides an object-oriented approach to working with databases.

Here is an example of creating a query using MySQLi:

Connect to the database
:


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

Create the query:


$sql = "SELECT * FROM table_name WHERE column_name = 'value'";

Execute the query :


$result = $conn->query($sql);

Handle the result:


if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}

Close the connection :


$conn->close();

Note that this is a basic example, and you can modify the query as needed depending on your specific requirements. It is also important to sanitize user input to prevent SQL injection attacks.
Post Answer