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.
Below is a PHP script that demonstrates how to implement pagination when displaying records from…
Below is a simple PHP script that demonstrates how to search a MySQL database table…
Transferring a WordPress site to a new domain involves several detailed steps to ensure that…
Creating client-server programs in C++ helps in understanding network programming and communication between applications over…
Creating a bookmark system for WordPress can range from simple solutions to more complex ones.…
The robots.txt file is used by websites to communicate with web crawlers and bots about which parts…