When a client requests a PHP file, the server completes three main steps in sequence: parsing, executing, and outputting.
The server first parses the PHP code, converting the script into executable instructions. PHP files start with <?php and end with ?>.
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.
Once execution finishes, the server sends the result back to the client, usually as HTML, JSON, XML, or images.
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.
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.
SQL injection is a common security threat for databases. Effective prevention methods include:
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.