0

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.

2 Answers2

2

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.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
1

You are not executing your sql insertcode. After this line:

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

Add these line:

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
mertizci
  • 538
  • 3
  • 12