How can PHP be used to interact with a MySQL database to execute commands in a console-like interface?
To interact with a MySQL database using PHP in a console-like interface, you can use the mysqli extension to establish a connection to the database and execute SQL commands. You can create a simple command-line interface that prompts the user for input and executes the corresponding SQL command.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Command-line interface
while (true) {
echo "Enter SQL command (or type 'exit' to quit): ";
$input = readline();
if ($input == 'exit') {
break;
}
$result = $conn->query($input);
if ($result === TRUE) {
echo "Command executed successfully.\n";
} else {
echo "Error: " . $conn->error . "\n";
}
}
// Close connection
$conn->close();
?>
Related Questions
- What potential security risks are involved in using $_GET to retrieve user information for displaying on a page?
- What are some best practices for securing a login system in PHP to prevent unauthorized access?
- Are there any best practices for handling arrays with multiple dimensions in PHP to avoid losing values or creating additional levels?