使用 PHP 在 MySQL 中发布存储选项值

Issue storing option value in MySQL using PHP

我正在尝试使用 POST 方法将表单内容提交到预先创建的 MySQL table。表单的每个部分都有不同的输入类型,包括 datetimenumberoption 值和 i无法找出我的代码的问题。任何帮助将不胜感激。 HMTL 和 PHP 低于...TIA。

PHP 代码:

<?php

    $servername = "localhost";
    $username = "root";
    $password = "cornwall";

    $con=mysqli_connect('localhost','root','cornwall','ibill');
    // This code creates a connection to the MySQL database in PHPMyAdmin named 'ibill':

    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    // The connection is then checked, if it fails, an echo is sent back to the page stating a connection error.

    if($_POST['formSubmit'] == "Submit") 
    {
       $typeofactivity = $_POST['typeofactivity'];
       $employer = $_POST['employer'];
       $datetime = $_POST['datetime'];
       $amount = $_POST['amount'];
       $errorMessage = "";

       // - - - snip - - - 
    }

        if(empty($typeofactivity)) {
          $errorMessage .= "<li>You forgot to enter an activity!</li>";
       }
       if(empty($employer)) {
          $errorMessage .= "<li>You forgot to enter an employer!</li>";
       }
       if(empty($datetime)) {
          $errorMessage .= "<li>You forgot to select the time and date!</li>";
       }
       if(empty($amount)) {
          $errorMessage .= "<li>You forgot to select the amount of the session!</li>";
       }

       $record_session = "INSERT INTO session_details (typeofactivity, employer, datetime, amount) VALUES ('$typeofactivity', '$employer', '$datetime', '$amount')"
       mysql_query($sql);
    }



    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);

    ?>

HTML:

<!--********************************RECORD SESSION PAGE************************************-->
<!--***************************************************************************************-->

<!--********************************HEADER**********************************************-->
<div data-role="page" id="sessionrecord">
    <div data-role="header" data-id="foo1" data-position="fixed">
    <div class='cssmenu'>
      <ul>
        <li class='active'><a href='#home'>Home</a></li>
        <li><a href='#sessionrecord'>Record a Session</a></li>
        <li><a href='#viewsessions'>View Sessions</a></li>
        <li><a href='#email'>E-mail an Invoice</a></li>
      </ul>
    </div>
  </div><!-- /header -->
<!--********************************HEADER**********************************************-->

<!--********************************MAIN**********************************************-->
  <div data-role="main" class="ui-content">

    <img class="mainlogo" src="/projects/ibill_v3/img/ibill logo.png" alt="iBill Logo" width="250" height="190">

        <section class="maincontent">
          <h1>Record a session using the form below</h1>
            <form method="post" action="record_session.php" id="sessionRecord">
              <fieldset>
                  <select name="typeofactivity" id="typeofactivity" data-native-menu="false">
                    <option>Type of Session</option>
                    <option value="surf">Surf</option>
                    <option value="coast">Coasteer</option>
                    <option value="bodyboard">Bodyboard</option>
                    <option value="climbing">Cornish Challenge</option>
                  </select>
              </fieldset>
              <fieldset>
                  <select name="employer" id="employer" data-native-menu="false">
                    <option>Employer</option>
                    <option value="nac">Newquay Activity Centre</option>
                    <option value="coastline">Coastline Coasteer</option>
                  </select>
              </fieldset>
                  <label for="datetime">Date and Time of Session</label>
                  <input type="datetime-local" data-clear-btn="false" name="datetime" id="datetime" value="">
                  <label for="amount">Amount (GBP)</label>
                  <input type="number" data-clear-btn="true" name="amount" id="amount" value="">
                <div id="submitbutton">
                  <input type="submit" name="formSubmit" value="Submit">
                </div>
            </form>

        </section>
  </div>
<!--********************************MAIN**********************************************-->

<!--********************************FOOTER**********************************************-->
  <div data-role="footer">
    <footer class="footer">
        <p>awilliams&copy;</p>
    </footer>
  </div>
</div>
<!--********************************FOOTER**********************************************-->

<!--********************************END OF RECORD SESSION PAGE************************************-->
<!--***************************************************************************************-->

多个问题

  1. 没有input sanitization

    $typeofactivity = $_POST['typeofactivity'];
    $employer = $_POST['employer'];
    $datetime = $_POST['datetime'];
    $amount = $_POST['amount'];
    
    // // // // // // // // // // // 
    
    $record_session = "INSERT INTO session_details (typeofactivity, employer, datetime, amount) VALUES ('$typeofactivity', '$employer', '$datetime', '$amount')"
    
  2. 缺少行尾;

    $record_session = "INSERT INTO session_details (typeofactivity, employer, datetime, amount) VALUES ('$typeofactivity', '$employer', '$datetime', '$amount')"
    
  3. 额外}

       // - - - snip - - - section.
    }
    
  4. $sql 是一个未声明的变量

    mysql_query($sql);
    
  5. mysql_query is the wrong API to use with MySQLi连接

    mysql_query($sql);
    
  6. 未使用的变量 $servername$username$password

    $servername = "localhost";
    $username = "root";
    $password = "cornwall";
    
    $con=mysqli_connect(['localhost','root','cornwall','ibill');
    
  7. root 应仅用于管理

    $username = "root";
    

可能的解决方案

<?php

// validate inputs exist first
$errorMessage = "";

// check if empty to avoid unused variable notice
if(empty($_POST['typeofactivity'])) {
$errorMessage .= "<li>You forgot to enter an activity!</li>";
} else $typeofactivity = $_POST['typeofactivity'];

if(empty($_POST['employer'])) {
$errorMessage .= "<li>You forgot to enter an employer!</li>";
} else $employer = $_POST['employer'];

if(empty($_POST['datetime'])) {
$errorMessage .= "<li>You forgot to select the time and date!</li>";
} else $datetime = $_POST['datetime'];

if(empty($_POST['amount'])) {
$errorMessage .= "<li>You forgot to select the amount of the session!</li>";
} else $amount = $_POST['amount'];


// don't bother with database unless all form fields have been posted
if ( empty($errorMessage) ){

  /*

    PHPMyAdmin is a tool to administer a MySQL database management system
    https://www.phpmyadmin.net/

    -- run these commands as root

    -- create a new user to run this page
    CREATE USER 'phpSessionRecord'@'localhost' IDENTIFIED BY 'lXfyYMGr4npolvbb';

    -- grant user minimal privileges
    -- https://en.wikipedia.org/wiki/Principle_of_least_privilege
    GRANT INSERT ON ibill.session_details TO 'phpSessionRecord'@'localhost';

  */

  $servername = "localhost";
  $username = "phpSessionRecord";
  $password = "lXfyYMGr4npolvbb";
  $databasename = "ibill";

  // create a MySQLi connection to the MySQL database
  $con = new mysqli($servername, $username, $password, $databasename);

  // stop the script if connection failure and print out error message
  if ($con->connect_error)
    die( "Failed to connect to MySQL: " . $con->error() );

  // parameterized SQL statement string
  $record_session = "
    INSERT INTO session_details
      (typeofactivity, employer, datetime, amount)
    VALUES (?, ?, ?, ?)
  ";

  // prepare the statement
  if (!($stmt = $con->prepare($record_session))) {
    die( "Prepare failed: " . $con->errno);
  }

  // bind the parameters as datatypes in same order as the question marks
  // VALUES (?, ?, ?, ?) : (string, string, string, decimal)
  $stmt->bind_param('sssd', $typeofactivity, $employer, $datetime, $amount);

  // execute or die
  if (!$stmt->execute()) {
    die( "Execute failed: " . $stmt->errno;

  /** Error reporting */
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);

} else echo $errorMessage;