Home > OS >  How do I get my form informations to my database?
How do I get my form informations to my database?

Time:12-12

I'm a French student, and I'm struggling to get my form to work, and send the informations I need to my database.

Here is my HTML form (don't mind the AngularJS floating around) :

         <form action="index.php" method="GET">
                <fieldset>
                    <legend> Votre recommandation </legend>
                    <!-- Titre -->
                    <label for="titre" >Titre <span>*</span></label><br>
                    <input ng-model="titre" id="titre" type="text" required><br>

                    <!-- Résumé -->
                    <label for="resume" >Résumé <span>*</span></label><br>
                    <input ng-model="resume" id="resume" type="text" required><br>

                    <!-- Catégorie-->
                    <label for="categorie" >Catégorie <span>*</span></label><br>

                    <input ng-model="categorie" type="radio" name="categorie" value="dev" required>
                    <label for="dev">Dév</label>

                    <input ng-model="categorie" type="radio" name="categorie" value="graphisme" required>
                    <label for="graphisme">Graphisme</label>

                    <input ng-model="categorie" type="radio" name="categorie" value="comm" required>
                    <label for="comm">Comm'</label>

                    <input ng-model="categorie" type="radio" name="categorie" value="divers" required>
                    <label for="divers">Divers</label><br><br>


                    <!-- Résumé -->
                    <label for="pointFort1" >Point fort n°1 <span>*</span></label><br>
                    <input ng-model="pointFort1" id="pointFort1" type="text" required><br>

                    <label for="pointFort2" >Point fort n°2 <span>*</span></label><br>
                    <input ng-model="pointFort2" id="pointFort2" type="text" required><br>

                    <label for="pointFort3" >Point fort n°3 </label><br>
                    <input ng-model="pointFort3" id="pointFort3" type="text"><br><br>


                    <label for="url" ><i ></i> URL du site
                        <span>*</span></label><br>
                    <input ng-model="url" id="url" type="text" required>

                    <!-- Submit-->
                    <button type="submit"><i ></i> Envoyer</button>

                </fieldset>
            </form>

In my index.php, I've written this SQL request :

    <?php

    $titre=$_POST["titre"];
    $resume=$_POST["resume"];

    $categorie=$_POST["categorie"];

    $pointFort1=$_POST["pointFort1"];
    $pointFort2=$_POST["pointFort2"];
    $pointFort3=$_POST["pointFort3"];

    $url=$_POST["url"];

    $db= new PDO( 'mysql:host=localhost; dbname=mmi_db; port=8889; charset=utf8', 'root', 'root');
   
    $plz= "SELECT titre FROM mmitoolbox";
    $ok = $link -> query($plz);
    $ok -> execute();
    $info=$ok->fetch(PDO::FETCH_ASSOC);
    echo($info);

    $sql="INSERT INTO `mmitoolbox` (`titre`, `resume`, `categorie`, `pointFort1`, `pointFort2`, `pointFort3`, `url` ) VALUES ('$titre', '$resume', '$categorie', '$pointFort1', '$pointFort2', '$pointFort3', '$url');";
    
    $req = $link -> query($sql);
?>

However, when submitting my form, nothing gets to my database. It's like it's not even linked to it. I'm using phpMyAdmin and MAMP.

Thank you for your time!

CodePudding user response:

There 's so much wrong with your code ...

Wrong request method in form

First of all you 're sending all your input data via get request to your index.php file. In your PHP code you 're trying to access post data, although your data has been send via get request. That means all your input data is not there, because the $_POST superglobal is empty. To fix this, just change the method attribute of your form element to post.

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

Server side validation

Furthermore you should validate the user input. What happens, if the data contains not what you 're expecting? Never ever trust user data. Client side validation with required attributes is worth nothing, when a user manipulates html source code via console. Again: Do NOT trust user data!

if (!strlen($_POST['value'])) {
    throw new \UnexpectedValueException('value is empty!');
}

Check all your received values and do not execute database related stuff until all data is valid.

Always check for errors with PDOException

What exactly do you expect, when the connection to your database is errorneous? If you haven 't turn on your error reporting you 'll never know what exactly went wrong. The documentation of the PDO::__construct() method says, that it will throw a PDOException instance, if something went wrong. So just wrap your PDO initialization in a try catch block.

try {
    $pdo = new \PDO(...);
    // put your database statements here
} catch {\PDOException $e} {
    echo "<pre>";
    var_dump($exception);
    echo "</pre>";
}

Always check the return value of a PDO query

What do you guess would happen, if your query method fails? Right. Nothing. Because you do not check the return value. It just runs into an error and you 'll never know, what really happend. The documentation of PDO::query() describes the return type as PDOStatement or false. Just use it.

$result = $pdo->query('...');
if ($result === false) {
    // ooops! query failed! some error handling here ...
}

Never ever put user data directly in a SQL string

Your SQL insert statement is wide open for sql injection. In the worst case someone is able to delete your whole database or read out all it 's contents. Putting data, that was sent by a user request directy in a sql string is the worst, that someone can do. NEVER DO IT! Just use prepared statements. They will escape the data for you.

// 
$value1 = $_POST['some_user_input_1'];
$value2 = $_POST['some_user_input_2'];

try {
     $pdo = new \PDO(...);
     $sql = "INSERT INTO table (column1, column2) VALUES (:value1, :value2)";
     $stmt = $pdo->prepare($sql);
     $stmt->execute([
         'value1': $value1,
         'value2': $value2,
     ]);
} catch (\PDOException $e) {
    // your error handling
}

CodePudding user response:

You need to execute the command in an if statement like so:

$req = $link->query($sql);
if($req) {
  echo "Executed";
} else {
  echo "Error";
}

And if you don't want to do it with a variable do this:

if($link->query($sql)) {
  echo "Executed";
} else {
  echo "Error";
}
  • Related