Friday, 31 August 2018

The PHP code does not issue a request to the database


I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:


function Insert () {
        if (XMLHttpRequestObject) {
            XMLHttpRequestObject.open("POST","list_insert.php");
            XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            XMLHttpRequestObject.onreadystatechange = function() {
                if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                    var returnedData = XMLHttpRequestObject.responseText;
                    var messageDiv = document.getElementById('messageDiv');
                    messageDiv.innerHTML = returnedData;
                }
            }
            var item = document.getElementById('items').value;
            var desc = document.getElementById('description').value;

            var data = item + '|' + desc + '|';

            XMLHttpRequestObject.send("data=" + data);
        }
        return false;
    }

This is the php code for list_insert:
<?php
    include "function_list.php";
    $myData = $_POST['data'];
    $datetime = date('Y-m-d H:i:s');
    list($items,$description) = explode ('|',$myData);

    $statement = "INSERT INTO record ";
    $statement .= "(items,description) ";
    $statement .= "VALUES (";
    $statement .=  "'".$items."', '".$description."')";
    print $statement;
    insert($statement);
    print "done";
?>

My php function to insert into the db (function_list):
<?php
    $con=mysqli_connect("localhost","shop");
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    function insert($statement) {
        global $con;
        mysqli_query($con,$statement);
    }
?>

When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated, thank you.

Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);

$$items = $_POST['items'];
$description = $_POST['desc'];

0 comments:

Post a Comment