W3docs

Send html form data to sql database via php (using mysqli)

To send HTML form data to a SQL database using PHP, you will need to use the mysqli (MySQL Improved) extension in PHP.

To send HTML form data to a SQL database using PHP, you will need to use the mysqli (MySQL Improved) extension in PHP. First, create an HTML form to collect the data:

<form method="POST" action="process.php">
  <input type="text" name="name" placeholder="Name">
  <input type="email" name="email" placeholder="Email">
  <textarea name="message" placeholder="Message"></textarea>
  <button type="submit">Submit</button>
</form>

Then, handle the submission in your PHP script. Note that all PHP code below should be in the same file to ensure variables persist correctly:

  1. Connect to the database using the mysqli_connect() function

Connecting to the MySQL database with mysqli_connect() function

<?php
// 1. Connect to the database
$conn = mysqli_connect("hostname", "username", "password", "database_name");

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

// 3. Retrieve the form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// 4. Create a prepared SQL query to insert the form data
$sql = "INSERT INTO table_name (name, email, message) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($conn, $sql);

// 5. Execute the query
mysqli_stmt_bind_param($stmt, "sss", $name, $email, $message);
if (mysqli_stmt_execute($stmt)) {
  echo "New record created successfully";
} else {
  echo "Error: " . mysqli_stmt_error($stmt);
}

// 6. Close the statement and connection
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

It is important to note that this is a very basic example and you should take security measures such as using prepared statements (as demonstrated above) and validating user input to prevent SQL injection attacks.