PHP is a popular programming language for creating dynamic websites and working with databases. Here are some examples of database queries in PHP:
1. Connecting to a database:
“`php
$servername = “localhost”;
$username = “your_username”;
$password = “your_password”;
$dbname = “your_database”;
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
“`
2. Selecting data from a table:
“`php
$sql = “SELECT * FROM users”;
$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”] . “, Email: ” . $row[“email”] . “
“;
}
} else {
echo “0 results”;
}
“`
3. Inserting data into a table:
“`php
$name = “John Doe”;
$email = “john@example.com”;
$sql = “INSERT INTO users (name, email) VALUES (‘$name’, ‘$email’)”;
if ($conn->query($sql) === true) {
echo “New record created successfully”;
} else {
echo “Error: ” . $sql . “
” . $conn->error;
}
“`
4. Updating data in a table:
“`php
$id = 1;
$name = “Jane Doe”;
$sql = “UPDATE users SET name=’$name’ WHERE id=$id”;
if ($conn->query($sql) === true) {
echo “Record updated successfully”;
} else {
echo “Error updating record: ” . $conn->error;
}
“`
5. Deleting data from a table:
“`php
$id = 1;
$sql = “DELETE FROM users WHERE id=$id”;
if ($conn->query($sql) === true) {
echo “Record deleted successfully”;
} else {
echo “Error deleting record: ” . $conn->error;
}
“`
Note: It is important to protect against SQL injection by using prepared statements or sanitizing user input before executing queries.