How can PHP be used to extract a variable from a URL and utilize it for database queries?
To extract a variable from a URL and use it for database queries in PHP, you can use the $_GET superglobal array to retrieve the variable value from the URL query string. You can then sanitize the input to prevent SQL injection attacks and use the variable in your database query to fetch relevant data.
// Extracting variable from URL
$variable = $_GET['variable'];
// Sanitize the input
$variable = filter_var($variable, FILTER_SANITIZE_STRING);
// Database query using the variable
$query = "SELECT * FROM table WHERE column = '$variable'";
$result = mysqli_query($connection, $query);
// Process the result
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
// Process each row
}
} else {
echo "Error executing query: " . mysqli_error($connection);
}