cassandra cassandra - 3 years ago 92
SQL Question

Error when posting data into SQL database from form

I'm trying to post data into an SQL database from a form.
I really don't understand what I am missing...
I tried several things I managed to make it work once but the form was only adding the id and it was leaving the other fields blank. Now it doesn't work at all.

My form is this

<form action ="addOutfit.php" method="post">

<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" placeholder="" value="">
</div>

<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" id="description" value=""></textarea>
</div>

<button type="submit" class="btn btn-default">Send</button>
</form>


and my code is this

<?php
require("pdo.php");
$_POST['title'] = "";
$_POST['description'] = "";


if (isset($_POST["submit"])){

$title = $_POST['title'];
$description = $_POST['description'];



$sql = "INSERT INTO outfit (title, description)
VALUES('$title', '$description')";
$statement = $pdo->prepare($sql);

$statement->execute([
'title' => $title,
'description' => $description
]);
};
?>

Answer Source

Changes:-

  1. provide name attribute to all your input fields.

  2. either provide name and value attribute to button, or check with POST data values of input field (more preferable).

So your code will be like below:-

<form action ="addOutfit.php" method="post"> 

<div class="form-group">
    <label for="title">Title</label>
    <input type="text" class="form-control" name = "title" id="title" value="">
</div>

<div class="form-group">
    <label for="description">Description</label>
    <textarea class="form-control" rows="3" name= "description" id="description" value=""></textarea>
</div>

     <button type="submit" class="btn btn-default">Send</button>
</form>


<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those error
require("pdo.php"); 
if (isset($_POST['title']) && isset($_POST['description'])){  // check actual input data not submit button

    $title = $_POST['title'];
    $description = $_POST['description'];
    $sql = "INSERT INTO outfit (title, description) VALUES('$title', '$description')";
    $statement = $pdo->prepare($sql);

    $statement->execute(['title' => $title,'description' => $description]);
}
?>

Note:- checking db connectivity is your responsibility. I don't know what code you have in "pdo.php". Good-luck.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download