PHP is a popular programming language used for web development. It can be used to connect and interact with MySQL databases.
To connect to a MySQL database in PHP, you can use the mysqli or PDO extensions. Here's an example of connecting to a MySQL database using mysqli:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Replace "your_username", "your_password", and "your_database" with your actual database credentials.
Once connected, you can perform various database operations using PHP, such as querying data, inserting records, updating records, and deleting records. Here's an example of querying data from a table:
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Replace "your_table" with the actual table name from your database.
Remember to handle errors and sanitize user input to prevent SQL injection attacks.
上一篇:php mysqlpdo
下一篇:php模糊查询mysql
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站