• I am looking to create an online job filing system for my company and to do so am trying to create this as a sort of intranet system with wordpress.

    I have an inital for that I enter the job details in to and a tab next to this form which allows me to view all jobs which have been entered.

    In order for the details to be saved and not lost after refresh I need the form input to be saved to the mySQL database table which I have created.

    The code I have used:

    The form:

        <div class="addjob tab-pane show active" id="home" role="tabpanel" aria-labelledby="home-tab">
            <h2>Add Job</h2>
            <form id="dataForm" name="dataform" method="POST" action="wp-content/themes/mytheme/database.php">
    	    <span>
    	        <label>Job Date:</label>
    		<input class="add-date" type="date" placeholder="Placeholder Text" name="adddate">
    	    </span>
    	    <span>
    	        <label>Client Name:</label>
    		<select name="addclient" class="limitedNumbChosen add-client" multiple="false">
    		    <option value="1">ClientA</option>
    		    <option value="2">ClientB</option>
    		</select>
    		<div id="add-company" class="fas fa-plus"> Add New Client</div>
    	    </span>
                <span>
    	        <label>Contact Name:</label>
    		<input class="add-contact" type="text" placeholder="John Doe"name="addcontact">
    	    </span>
    	    <span>	
    	        <label>From:</label>
    		<input id="add_from" class="add-from" type="text" placeholder="Postcode from" name="addfrom">
    	    </span>
    	    <span>
    	        <label>To:</label>
    		<input class="add-to" type="text" placeholder="Postcode to" name="addto">
                </span>
    	    <span>
    	        <label>Who Done Job:</label>
    		<select name="subbie_name" class="limitedNumbSelect2 add-driver" multiple="true">
    		    <option value="1">Dave</option>
    		</select>
    		<div id="add-subbie" class="fas fa-plus"> Add Subbie </div>
    	    </span>
    	    <span>
    	        <label>Income (£):</label>
    		<input class="add-income" type="number" placeholder="£120" name="addincome">
    	    </span>
    	    <span>
    	        <label>Driver Payment (£):</label>
    		<input class="add-payment" type="number" placeholder="£100" name="addpayment">
    	    </span>
    	    <span>
    	        <button id="submit" type="submit" value="submit">Submit</button>
    	    </span>
    	</form>
        </div> 

    The PHP:

        <?php
        
        //Register variables
        
        $adddate = $_POST['adddate']
        $addcontact = $_POST['addcontact']
        $addfrom = $_POST['addfrom']
        $addto = $_POST['addto']
        $addincome = $_POST['addincome']
        $addpayment = $_POST['adddate']
        $addsubbie = $_POST['addsubbie']
        $addclient = $POST['addlient']
    
        //connect with Database
    
        $host_name = 'xxx.hosting-data.io';
            $database = 'xxx';
            $user_name = 'xxx';
            $password = 'xxx';
            $connect = mysql_connect($host_name, $user_name, $password, $database);
    
        //Send to database
    
        if (mysql_errno()) {
            die('<p>Failed to connect to MySQL: '.mysql_error().'</p>');
        }     else {
                  $wpdb = $connect->prepare("insert into add_job(adddate, addcontact, addfrom, addto, addincome, addpayment adddriver addcompany)
                          values(?, ?, ?, ?, ?, ?, ?, ?,)");
                  $wpdb->bind_param("ssssiiss",  $adddate, $addcontact, $addfrom, $addto, $addincome, $addpayment, $addsubbie, $addcoclient) ;
                  $wpdb->execute();
                  echo "Job Submited"
                  $wpdb->close();
                  $connection->close();
              }

    I have never tried to send info to a database. Any help would be much appreciated

Viewing 8 replies - 16 through 23 (of 23 total)
  • Thread Starter Supplement Genie

    (@supplementgenie)

    @joyously @bcworkz yeah the mysqli was misspelt but I amended that earleir, not that it made any difference lol.

    no the way it was shown in the question was wrong, I tried to edit but was too late. I had added ” to the terms in the brackets on the lower one but all it done was add grey areas lol… And this is one big grey area for me

    I feel as though I have used the correct code I cannot see anything that I should change.
    But I am unsure how to determine what is causing the error.

    When I check console and params, it gives all the right parameters with the correct titles.

    But the php doesnt seem to take them and insert them into the table. I am unsure how to debug this as the echo statements I have added dont seem to work which makes it harder to determine where the error lies

    Anything echoed in an ajax call comes back in the response.
    You should use the PHP error_log function.

    Thread Starter Supplement Genie

    (@supplementgenie)

    @joyously @bcworkz yeah the mysqli was misspelt but I amended that earleir, not that it made any difference lol.

    I now have error messages showing…

    Have done a bit of tinkering and the error message I am getting:

    Error: INSERT INTOadd_job(id,adddate,addcontact,adda,addb,addincome,addpayment,addsubbie,addclient`) VALUES (NULL ‘2019-09-06’, ‘test’, ‘test’, ‘test’, ‘test’, ‘test’, ‘test’, ”)
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ”2019-09-06′, ‘test’, ‘test’, ‘test’, ‘test’, ‘test’, ‘test’, ”)’ at line 2`

    I have changed to code to:

    JS

        jQuery(document).ready(function () {
        $("#addsubmit").click(function(e) {
            e.preventDefault();
            e.stopPropagation();
    
            var date = document.getElementById("adddate").value;
            var contact = document.getElementById("addcontact").value;
            var a = document.getElementById("adda).value;
            var b = document.getElementById("addb").value;
            var income = document.getElementById("addincome").value;
            var payment = document.getElementById("adddate").value;
            var subbie = document.getElementById("addsubbie").value;
            var client = document.getElementById("addclient").value;
    
            // Returns successful data submission message when the entered information is stored in database.
            var dataForm = 'date1=' + date + '&contact1=' + contact + '&a1=' + a + '&b1=' + b + '&income1=' + income + '&payment1=' + payment + '&subbie1=' + subbie + '&client1=' + client;
            if (date == '' || contact == '' || a == '' || b == '' || income == '' || payment == '' || subbie == '' || client == '') {
            alert("Please Fill All Fields");
            } 
            else {
            // AJAX code to submit form.
                jQuery.ajax({
                    type: "POST",
                    url: 'wp-content/themes/EazyFreight/database.php',
                    data: dataForm,
                    dataType:"json", 
                    success:function(strMessage) {
                        $("#message").text(strMessage);
                        $("#dataForm")[0].reset();
                    }
                });
                return false;  
            }
        });

    PHP

    <?php
    
        //Register variables
        $adddate = $_POST['date1'];
        $addcontact = $_POST['contact1'];
        $adda = $_POST['a1'];
        $addb = $_POST['b1'];
        $addincome = $_POST['income1'];
        $addpayment = $_POST['payment1'];
        $addsubbie = $_POST['subbie1'];
        $addclient = $POST['client1'];
    
        //connect with Database
        if (!empty($adddate) || !empty($addcontact) || !empty($adda) || !empty($addb) || !empty($addincome) || !empty($addpayment) || !empty($addsubbie) || !empty($addclient)){
            $host_name = 'xxx.hosting-data.io';
            $database = 'xxx';
            $user_name = 'xxx';
            $password = 'xxx';
            $conn = mysqli_connect($host_name, $user_name, $password, $database);
        }
        // Check connection
    
        if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
        }
    
        $sql = "INSERT INTO <code>add_job</code>(<code>id</code>, <code>adddate</code>, <code>addcontact</code>, <code>adda</code>, <code>addb</code>, <code>addincome</code>, <code>addpayment</code>, <code>addsubbie</code>, <code>addclient</code>)
        VALUES (NULL '$adddate', '$addcontact', '$adda', '$addb', '$addincome', '$addpayment', '$addsubbie', '$addclient')";
        
        if (mysqli_query($conn, $sql)) {
            echo "New record created successfully";
        } 
        else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
        mysqli_close($conn);
        die();

    Have you any idea what might cause the error? or the best way to deb

    You are going to have to read the error and do what it says. There is a missing comma after NULL in your SQL. Not sure what else.

    Thread Starter Supplement Genie

    (@supplementgenie)

    @joyously
    Simple fix, thank you, thats it working now ??

    In all honesty in the few replies youve given me you have been a massive help… You have helped me to also see that when I am debugging I spend too much time looking at the code and what it is saying as above, my code seemed to have all the right info etc… I dont spend enough time looking at the other details such as punctuation which can have a massive effect on the code.

    I looked at that over and over and never noticed the missing ,

    Thank you again and sorry for my negligence ?? lol

    Now you can focus on plugging the security holes that are in your code.
    You need to sanitize all user input, validate that it is the correct type for the field, and use prepare on your SQL. Also, use of a nonce and checking for user capability to write to the database would be good, but your code is outside of WP.
    With a PHP file sitting on your server, anyone can invoke it directly, especially if the checks are in some other file.

    Thread Starter Supplement Genie

    (@supplementgenie)

    @joyously @bcworkz Thank you for the help. The form is intended to be used internally and only logged-in users within the company will have access so im hoping that security won’t be an issue.

    Can I ask, I have tried a number of different things but apparently none of them being the right thing.

    based on the code, I have… After form submission, I am keen for the form to be cleared however as it stands, once submitted, all of the form fields remain populated.

    The jQuery/Ajax, passes all the details over for PHP to process so I am thinking that PHP will be the better place to put the code…

    I have tried adding at the end:

    echo:"<script></script>"

    and putting different code in after the

    if (mysqli_query($conn, $sql)) {
            echo "New record created successfully";
        } 

    as well as after the ajax:

    success: function() {
                        alert('Message sent');
                        document.getElementById('dataForm').reset();
                    }

    Is there a better way to do this that might actually work? lol

    Update…

    Solved the problem..

    success: function() {
                        alert('Message sent');
                    },
                    complete: function(){
                        $('#dataForm').each(function(){
                            this.reset();   //Here form fields will be cleared.
                        });
                    }

    The bit that I cant get to clear is the <select> areas, they remain populated. however if I fill in the other areas and then press submit, although they have values in them, the script doesn’t recognsise that theyre there so I need to clear the values myself and re-enter

    The form is intended to be used internally and only logged-in users within the company will have access so im hoping that security won’t be an issue.

    The whole point of a hack is to do something unintended.

    With a PHP file sitting on your server, anyone can invoke it directly, especially if the checks are in some other file.

Viewing 8 replies - 16 through 23 (of 23 total)
  • The topic ‘Saving data from form to Database Table’ is closed to new replies.