Juan dela Cruz Juan dela Cruz - 2 months ago 12
PHP Question

php Data not stored in mySQL database using XAMPP

I have this code and I am using the latest version of XAMPP:

filename: store.html

<!DOCTYPE html>

<html>
<body>

<form action="store.php" method="post">
User input: <input type="text" name="userinput"><br>
<input type="submit">
</form>

</body>
</html>


filename: store.php

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

$input = $_POST["userinput"];


$sql = "INSERT INTO table_1 (s_num)
VALUES ('$input')";


?>


Whatever I do, no data is added to the database. Please help. Thank you.

Answer

The problem here is that you never executed the query.

$sql = mysqli_query($conn,"INSERT INTO table_1 (s_num)
VALUES ('$input')");

if(!sql){

   echo "Error: " . mysqli_error($conn);

}

else{

   echo "Success";

}

Reference:


Your present code is open to SQL injection if user-input (other than yourself) ever gets involved.

Use prepared statements, or PDO with prepared statements, they're much safer.


Plus, seeing you are running this from your own machine, make sure you are accessing as http://localhost/file.php as opposed to file:///file.php.

Comments