Current Location: Home> Latest Articles> Detailed PHP File Execution Process and Practical Database Connection Code Examples

Detailed PHP File Execution Process and Practical Database Connection Code Examples

gitbox 2025-07-17

PHP File Execution Process

When a client requests a PHP file, the server completes three main steps in sequence: parsing, executing, and outputting.

Parsing the PHP File

The server first parses the PHP code, converting the script into executable instructions. PHP files start with <?php and end with ?>.

Executing the PHP Code

After parsing, the server executes the PHP script, processing variables, functions, and logic. During execution, the server differentiates between the code inside the script and the environment’s variables and functions to ensure correct operation.

Outputting the Result

Once execution finishes, the server sends the result back to the client, usually as HTML, JSON, XML, or images.

Basic PHP Database Connection Code

In PHP, connecting to a MySQL database is typically done using the mysqli extension. Here's an example:

$username = "username";
$password = "password";
$hostname = "hostname";
$database = "database_name";

// Create connection object
$conn = new mysqli($hostname, $username, $password, $database);

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

This code establishes a connection by passing the hostname, username, password, and database name. After a successful connection, you can execute SQL commands using $conn.

Example of Querying the Database

Below is a simple example using the mysqli object to run a query:

$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output each record
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "No results found";
}

$conn->close();

This code executes a SELECT query, iterates through the results, outputs each record, and finally closes the database connection.

Common Methods to Prevent SQL Injection

SQL injection is a common security threat for databases. Effective prevention methods include:

  • Using mysqli_real_escape_string() to escape user input
  • Using PDO with prepared statements and parameter binding

Here is an example of using PDO to prevent SQL injection:

$sql = "SELECT * FROM table_name WHERE name = :name";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($result);

$conn->close();

By preparing the SQL statement and binding parameters, this approach effectively prevents malicious SQL injection and protects data security.