PHP provides a set of functions to work with MySQL databases. As of the more recent versions, developers are encouraged to use the MySQLi or PDO_MySQL extensions instead of the older MySQL extension, as the latter is deprecated. Here, we’ll focus on MySQLi (MySQL Improved) functions, which provide both procedural and object-oriented interfaces for interacting with MySQL databases.
$mysqli = mysqli_connect("localhost", "username", "password", "database"); if (!$mysqli) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully";
mysqli_close($mysqli);
$result = mysqli_query($mysqli, "SELECT * FROM users"); if (!$result) { echo "Error: " . mysqli_error($mysqli); }
if ($result) { while ($row = mysqli_fetch_assoc($result)) { echo "Name: " . $row['name'] . "<br>"; } }
if ($result) { while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) { echo "Name: " . $row[1] . "<br>"; } }
$stmt = mysqli_prepare($mysqli, "SELECT name FROM users WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $userId); $userId = 1; mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $name); while (mysqli_stmt_fetch($stmt)) { echo "Name: $name<br>"; } mysqli_stmt_close($stmt);
$stmt = mysqli_prepare($mysqli, "INSERT INTO users (name, email) VALUES (?, ?)"); mysqli_stmt_bind_param($stmt, "ss", $name, $email); $name = "John Doe"; $email = "john@example.com"; mysqli_stmt_execute($stmt); echo "New record ID: " . mysqli_insert_id($mysqli);
$stmt = mysqli_prepare($mysqli, "UPDATE users SET email = ? WHERE id = ?"); mysqli_stmt_bind_param($stmt, "si", $email, $userId); $email = "john.updated@example.com"; $userId = 1; mysqli_stmt_execute($stmt); echo "Affected rows: " . mysqli_stmt_affected_rows($stmt);
$stmt = mysqli_prepare($mysqli, "DELETE FROM users WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $userId); $userId = 1; mysqli_stmt_execute($stmt); echo "Deleted rows: " . mysqli_stmt_affected_rows($stmt);
$result = mysqli_query($mysqli, "SELECT * FROM users"); echo "Number of rows: " . mysqli_num_rows($result);
These examples demonstrate the basic operations you can perform with MySQLi in PHP. The use of prepared statements is especially important for preventing SQL injection and ensuring better security for your database operations.
WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…
I. Project Overview The goal is to automate the process of notifying search engines (like…
1. Database Structure (MySQL) We'll need a database table to store information about our website's…
This explanation aims to provide a solid foundation for understanding the process and implementing your…
Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…
Comprehensive guide on creating a simple website analytics system using PHP, HTML, CSS, JavaScript, and…