-1

I am trying to use the POST method in order to submit the contents of a form to a pre-created MySQL table. There are different input types for each part of the form including datetime, number and option values and i can't figure out the problem with my code. Any help would be greatly appreciated. HMTL and PHP is below...TIA.

PHP CODE:

<?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************************************-->
<!--***************************************************************************************-->
Omar
  • 32,302
  • 9
  • 69
  • 112
asharoo85
  • 49
  • 10
  • 1
    what error are you getting? in what way does this not work? – gavgrif Apr 21 '16 at 22:58
  • you will have a lot more errors later if you don't sanitize your inputs – Jeff Puckett Apr 21 '16 at 23:01
  • initially, no errors are displaying, it is just producing a blank screen with the record_session.php URL. When i refresh the page it produces this error- Parse error: syntax error, unexpected 'mysql_query' (T_STRING) in C:\xampp\htdocs\projects\ibill_v3\html\record_session.php on line 40 – asharoo85 Apr 21 '16 at 23:03
  • yup, missing semicolon, see my answer – Jeff Puckett Apr 21 '16 at 23:04
  • you are also concatenating li's to the error message string, but i can't see either the ul tags or where your'e displaying the errors? – gavgrif Apr 21 '16 at 23:05
  • This is pointing towards the **mysql_query($sql);** syntax – asharoo85 Apr 21 '16 at 23:05

1 Answers1

3

multiple issues

  1. no 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. end of line missing ;

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

       // - - - snip - - - section.
    }
    
  4. $sql is an undeclared variable

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

    mysql_query($sql);
    
  6. unused variables $servername, $username, and $password

    $servername = "localhost";
    $username = "root";
    $password = "cornwall";
    
    $con=mysqli_connect(['localhost','root','cornwall','ibill');
    
  7. root should only be used for administration

    $username = "root";
    

possible solution

<?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;
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
  • thanks, added the ; but the error moved down to the next line.... – asharoo85 Apr 21 '16 at 23:09
  • Parse error: syntax error, unexpected '}', expecting end of file in C:\xampp\htdocs\projects\ibill_v3\html\record_session.php on line 41 – asharoo85 Apr 21 '16 at 23:10
  • yes. there is an extra `}` after the `mysql_query($sql);` delete that. – Jeff Puckett Apr 21 '16 at 23:12
  • or, by the looks of it, you probably want to delete the `}` after the `// - - - snip - - -` – Jeff Puckett Apr 21 '16 at 23:13
  • uh oh...all sorts of errors now :( – asharoo85 Apr 21 '16 at 23:15
  • that's ok, they'll teach you a lot. just work through them each one by one – Jeff Puckett Apr 21 '16 at 23:15
  • changed the last one you said and only one error now: Notice: Undefined index: formSubmit in C:\xampp\htdocs\projects\ibill_v3\html\record_session.php on line 15 – asharoo85 Apr 21 '16 at 23:16
  • if($_POST['formSubmit'] == "Submit") { $typeofactivity = $_POST['typeofactivity']; $employer = $_POST['employer']; $datetime = $_POST['datetime']; $amount = $_POST['amount']; $errorMessage = ""; – asharoo85 Apr 21 '16 at 23:17
  • you named your submit button `formSubmit`, so I don't think that actually gets posted to the server – Jeff Puckett Apr 21 '16 at 23:18
  • I've changed the `$_POST` validator and corrected those aforementioned errors with an updated answer. try this to see where it gets you next – Jeff Puckett Apr 21 '16 at 23:22
  • should i change it to my form id? – asharoo85 Apr 21 '16 at 23:22
  • well there are lots ways to validate, just try to get the insert working first, then you can focus on sanitizing. I've posted an updated answer – Jeff Puckett Apr 21 '16 at 23:25
  • okay thanks for your help, i tried your updated answer, now it just renders a blank screen and no errors, but no insert into the db. I will have a poke around and see what i can do – asharoo85 Apr 21 '16 at 23:29
  • This `mysql_query($sql);` is failing for 2 reasons. 1) Wrong API. 2) Wrong variable. So... => `mysqli_query($con, $record_session);` – Funk Forty Niner Apr 21 '16 at 23:29
  • Thanks Fred, actually just noticed the insert into the DB was working. Thanks @Jeff Pucket II too! – asharoo85 Apr 21 '16 at 23:40
  • @asharoo85 welcome but I can't see why you accepted the answer. He never made the change to what the query should be and this for future readers. I basically solved this in the end. – Funk Forty Niner Apr 22 '16 at 00:21
  • good call Fred, I've seen you around the php questions quite a bit and you're amazing, so feel free to edit my answers anytime. I've edited this answer with your winning input and converted into a wiki for anyone else to edit too - as I am sure there's still room for improvement – Jeff Puckett Apr 22 '16 at 04:07
  • aplogies, i thought i was accepting this as the answer from a mixture of both of your comments. Still getting to grips with stackoverflow, note taken for future use! – asharoo85 Apr 22 '16 at 14:42