How can a new column with predefined links be added to a table populated by an SQL query in PHP?
To add a new column with predefined links to a table populated by an SQL query in PHP, you can simply concatenate the links with the data retrieved from the query in the SELECT statement. This will create a new column with the predefined links for each row in the result set.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve data from a table
$sql = "SELECT id, name, CONCAT('http://example.com/', id) AS link FROM table_name";
$result = $conn->query($sql);
// Display the data with the new column containing predefined links
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th><th>Link</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td><a href='".$row["link"]."'>Link</a></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
Related Questions
- What best practices should be followed to prevent the creation of multiple SessionIDs in PHP applications?
- What are some best practices for dynamically populating dropdown options in PHP based on database values?
- How can PHP and CSS work together to achieve a consistent layout for displaying database entries in multiple tables?