PHP Input & Output: A Comprehensive Guide
PHP Input & Output: A Comprehensive Guide
PHP provides various ways to manage input and output operations, enabling you to interact with users, files, and databases. Here's a breakdown of common methods:
1. Outputting Data
You can use the echo or print statements to display data in your browser or command-line interface.
echo 'Hello World!';
print 'Hello World!';
2. Receiving User Input
PHP offers superglobal variables like $_GET, $_POST, and $_REQUEST to collect user input data.
$_GET: Used for data submitted through query strings in URLs.$_POST: Used for data submitted through HTML forms with thePOSTmethod.$_REQUEST: Combines data from both$_GETand$_POST.
Example using $_POST:
$name = $_POST['name'];
$email = $_POST['email'];
3. File Input & Output
You can utilize functions like file_get_contents and file_put_contents to read and write data to files.
Example:
// Read file contents
$fileData = file_get_contents('file.txt');
echo $fileData;
// Write data to file
$fileData = 'Hello World!';
file_put_contents('file.txt', $fileData);
4. Database Input & Output
PHP offers extensions like MySQLi and PDO to interact with databases, executing queries and updating data.
Example using MySQLi:
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'myDB';
$conn = new mysqli($servername, $username, $password, $dbname);
// Execute a query
$sql = 'SELECT * FROM users';
$result = $conn->query($sql);
// Display query results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo 'Name: ' . $row['name']. ' - Email: ' . $row['email']. '<br>';
}
} else {
echo '0 results';
}
$conn->close();
These examples showcase basic input and output operations in PHP. For more advanced techniques and detailed documentation, refer to the official PHP documentation or explore relevant tutorials.
原文地址: http://www.cveoy.top/t/topic/qwUw 著作权归作者所有。请勿转载和采集!