PHP PROGRAM TO STORE VALUE IN DATABASE USING TEXT BOX
Sure, here's a simple PHP program that allows you to store data into a database using a text box:
php<?php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get input values from form
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Prepare SQL statement to insert data into database
$sql = "INSERT INTO messages (name, email, message) VALUES ('$name', '$email', '$message')";
// Execute SQL statement and check for errors
if (mysqli_query($conn, $sql)) {
echo "Data stored successfully!";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
// Close database connection
mysqli_close($conn);
?>
<!-- HTML form to collect input values -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" value="Submit">
</form>
This program connects to a MySQL database and uses the mysqli_query()
function to insert the input values into a table named messages
. The input values are collected using an HTML form that submits the data to the PHP script when the user clicks the "Submit" button.
Note that this is a very basic example and you should add additional validation and security measures to your code if you plan to use it in a production environment.
Comments
Post a Comment