"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Thursday, January 25, 2024

Save Form data into Database

 Save Form data into Database

Step 1: First you have to create a database.

Step 2: create a table in database.

Step 3: you would need to connect to the database and execute an SQL query to insert the data. 

Explained Briefly:

Step 1: First you have to create a database.

start the XAMPP control panel
Start the Apache and MySQL both
Open the browser with following address  http://localhost/phpmyadmin/
create a database 


Give a database name




After giving the database name go to that database 

Step 2: create a table in database.





Step 3: you would need to connect to the database and execute an SQL query to insert the data. 

Ensure that you have created a database(your database, i,e; student) and  table (your_table, i.e; students) with columns (username, age, email) corresponding to the form fields(exactly match form fields name attribute value).

Also, make sure your database user has the necessary permissions to perform INSERT operations. 


Connection php with mysql(database connectivity Code in PHP)

$host = "localhost"; // replace with your database host 

$db_name = "your_database"; // replace with your database name 

$db_username = "your_username";//replace with your database username 

$db_password = "your_password"; //replace with your database password

 // Create a database connection

$conn = new mysqli($host, $db_username, $db_password, $db_name);

// Check the connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn-> connect_error);

    }


After Submit of form

if($_POST['submit'])) {

        $name = $_POST['name'];

        $age = $_POST['age'];

        $email = $_POST['email’];


…..

///rest of code

}



OR

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Collect form data

        $name = $_POST['name'];

        $age = $_POST['age'];

        $email = $_POST['email’];


…..

///rest of code

}


///rest of code or code for insert 

...

$sql= "INSERT INTO your_table (username, password, email) VALUES ('$username', '$password', '$email')";

    // Execute the query

    if ($conn->query($sql) === TRUE) {

        echo "<h2>Data saved successfully</h2>";

    } else {

        echo "Error: " . $sql . "<br>" . $conn->error;

    }

$conn->close();

....





No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template