How can PHP variables be used to store and display the results of MySQL queries for data manipulation?
To store and display the results of MySQL queries using PHP variables for data manipulation, you can use the mysqli extension in PHP. First, establish a connection to the MySQL database using mysqli_connect(). Then, execute the query using mysqli_query() and store the results in a variable. Finally, loop through the results and display them as needed.
// Establish connection to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Display results
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
mysqli_close($connection);
Related Questions
- How does the use of helper keys in PHP affect the overall performance and efficiency of database operations?
- What are the potential consequences of prematurely closing a MySQL connection in a PHP script?
- Are there any global settings or configurations in PHP that need to be considered when working with special characters in strings?