How connect mysqli with insert record using PHP

To connect to MySQL database using mysqli and insert a record using PHP, you can follow the steps below:

  1. Establish a connection to the MySQL database using mysqli_connect() function. The function takes four parameters: host, username, password, and database name. Here's an example code:


$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}


  1. Once you've established a connection, you can use the mysqli_query() function to execute the SQL query to insert the record. Here's an example code that inserts a record into a "users" table:

$sql = "INSERT INTO users (first_name, last_name, email) VALUES ('John', 'Doe', 'johndoe@example.com')";

if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}



In this example, the SQL query inserts a record with the first name, last name, and email values into the "users" table. The mysqli_query() function executes the query, and if it is successful, the message "Record inserted successfully" is displayed. If there is an error, the message "Error inserting record" along with the error message is displayed.

  1. After executing the query, close the database connection using the mysqli_close() function:

mysqli_close($conn);


That's it! You've now connected to MySQL using mysqli and inserted a record into a table using PHP.

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...