How can PHP scripts interact with databases like MySQL based on parameters passed through URLs?
PHP scripts can interact with databases like MySQL based on parameters passed through URLs by using the $_GET superglobal array to retrieve the parameters from the URL. These parameters can then be used in SQL queries to fetch, insert, update, or delete data in the database. It is important to sanitize and validate the input parameters to prevent SQL injection attacks.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve parameter from the URL
$id = $_GET['id'];
// Sanitize the input parameter
$id = mysqli_real_escape_string($conn, $id);
// Use the parameter in a SQL query
$sql = "SELECT * FROM table_name WHERE id = $id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>