Type Here to Get Search Results !

CRUD PHP MySQLi



To perform CRUD (Create, Read, Update, and Delete) operations using mysqli in PHP, you can use the following code snippets as examples:Connect to the MySQL database using mysqli:

php
<?php $servername = "localhost"; $username = "yourusername"; $password = "yourpassword"; $dbname = "yourdatabasename"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>

Create a record (CREATE operation) using mysqli:

php
<?php $sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>

Read data (READ operation) using mysqli:

php
<?php $sql = "SELECT column1, column2, column3 FROM table_name"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "column1: " . $row["column1"]. " - column2: " . $row["column2"]. " - column3: " . $row["column3"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?>

Update a record (UPDATE operation) using mysqli:

php
<?php $sql = "UPDATE table_name SET column1='newvalue1', column2='newvalue2', column3='newvalue3' WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?>

Note that you should replace table_name, column1, column2, column3, and id with your own values.

Delete a record (DELETE operation) using mysqli:
php
<?php $sql = "DELETE FROM table_name WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } $conn->close(); ?>
Tags

Posting Komentar

0 Komentar