Canonical: How to save HTML form data into MySQL database

前端 未结 1 1524
醉酒成梦
醉酒成梦 2021-01-01 00:52

This is a canonical question and answer for saving data from (HTML) form to MySQL database using PHP.

This applies to you if you are trying to do the following:

1条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 01:53

    First of all your PHP or HTML page should produce a form that user can interact with. In the most simple form it'd be something like:

    
    
     

    This will give your user a simple form with single input field and 'save' button. After clicking the 'save' button for content will be sent to your 'yourscript.php' using POST method.

    yourscript.php should implement the following:

    1. Accept and process the input from your form.
    2. Connect to your MySQL database.
    3. Store into the database.

    In most simplistic form this would be:

    
    
     
      Process and store
     
    
    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // Use prepared statements to mitigate SQL injection attacks.
        // See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php for more details
        $qry=$conn->prepare('INSERT INTO yourtable (yourcolumn) VALUES (:yourvalue)');
    
        // Execute the prepared statement using user supplied data.
        $qry->execute(Array(":yourvalue" => $yourfield));
    
    } catch (PDOException $e) {
        echo 'Error: ' . $e->getMessage() . " file: " . $e->getFile() . " line: " . $e->getLine();
        exit;
    }
    ?>
    

    Key takeaway here is to use prepared statements to avoid SQL injections attacks.

    0 讨论(0)
提交回复
热议问题