How can a PHP developer save a selected employee's name as a variable and use it in an SQL query to display specific data?
To save a selected employee's name as a variable and use it in an SQL query to display specific data, a PHP developer can utilize a form to allow the user to select the employee's name, save the selected name as a variable using $_POST, and then use this variable in an SQL query to fetch the specific data related to the selected employee.
<?php
// Assuming the form has a select input named 'employee_name'
if(isset($_POST['employee_name'])){
$selected_employee = $_POST['employee_name'];
// Establish a database connection
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to fetch specific data for the selected employee
$sql = "SELECT * FROM employees WHERE name = '$selected_employee'";
$result = $conn->query($sql);
// Display the fetched data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Employee ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();
}
?>
Keywords
Related Questions
- Can you recommend a reliable source for learning PHP that is more up-to-date than the book mentioned in the forum thread?
- What are the potential issues with nesting forms in PHP and how can they be avoided?
- What are the best practices for encrypting sensitive data, such as passwords, in PHP applications?