Link to home
Start Free TrialLog in
Avatar of David Schure
David Schure

asked on

INSERT Statement NOT Inserting

This statement worked then stopped...any clues?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_REQUEST);

try{
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
$client_id = $_REQUEST['client_id'];
try{
    $sql = "INSERT INTO `tbl_answers`(
        `client_id`, 
        `type`,
      `reasons`,
        `gender`,
      `on_gender`,
        `age`, 
        `sexual_orientation`,
      `on_sex`,
        `relationship`,
        `religious`,
      `on_religion`,
        `spiritual`,
      `on_spirit`,
        `therapy_before`, 
        `corona`, 
        `suicide`, 
        `panic`, 
        `medications`, 
        `pain`,
        `finances`, 
        `sleep`,
        `reference`) VALUES ( '" .
        $client_id . "', '" .
        $_REQUEST['type'] . "', '" .
        $_REQUEST['reasons'] . "', '" .
      $_REQUEST['gender'] . "', '" .
      $_REQUEST['tgender'] . "', '" .
        $_REQUEST['age'] . "', '" .
        $_REQUEST['sex'] . "', '" .
      $_REQUEST['tsex'] . "', '" .
        $_REQUEST['relationship'] . "', '" .
        $_REQUEST['religious'] . "', '" .
      $_REQUEST['treligious'] . "', '" .
        $_REQUEST['spiritual'] . "', '" .
      $_REQUEST['tspiritual'] . "', '" .
        $_REQUEST['counsel'] . "', '" .
        $_REQUEST['counsel1'] . "', '" .
        $_REQUEST['suicide'] . "', '" .
        $_REQUEST['panic'] . "', '" .
        $_REQUEST['medication'] . "', '" .
        $_REQUEST['pain'] . "', '" .
        $_REQUEST['finance'] . "', '" .
        $_REQUEST['sleep'] . "', '" .
        $_REQUEST['refer'] . "'
    )";
    if ($stmt = $pdo->prepare($sql)) {
        // $data = [
        //     'name' => $_REQUEST['name'],
        //     'street_number' => $_REQUEST['street_number'],
        //     'street' => $_REQUEST['street'],
        //     'city' => $_REQUEST['city'],
        //     'state' => $_REQUEST['state'],
        //     'zip_code' => $_REQUEST['zip_code'],
        //     'country' => $_REQUEST['country'],
        //     'email' => $_REQUEST['email'],
        // ];
    
        // $stmt->execute($data);
        $stmt->execute();
        $id = $pdo->lastInsertId();
    
        // var_dump($sql, $data, $id);
        
        echo "Record inserted successfully";
    
    } else {
        die("Could not prepare Statement");
    }
}catch(Exception $e){
    echo $e->getMessage();
}
?>

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey David,

What exactly does 'it stopped' mean ! Do you get errors, do you get any output, is anything being inserted, what happens when you uncomment the var_dump ? Too little info to go on really.
Probably because you have a value with an apostrophe in it somewhere.

You're not using parameter binding, so you're wide open to SQL injection.
Further to what gr8gonzo said - you seem to have had parameter binding in place, but for some reason, you've commented that out and gone back to coding your user input directly into the query - a big NO NO !
Avatar of David Schure
David Schure

ASKER

Hi, nothing happens when I click on Submit at the end....
https://audiodigz.com/Join-Us.php
I see what you mean about the binding......how to correct this?
Hey David,

Bit confused - the link you've just posted seems to have no bearing on the code you've posted. You've either posted the wrong code, or the wrong link!

As for binding, you need to use placeholders in your SQL and then pass the data in when you execute. In PDO, you can either use anonymous placeholders or named placeholders. If you use anonymous, you need to pass the data in the correct order. If you use named placeholders, you need to set the array key to match the placeholder, so either:

// with named placeholders
$stmt = $db->prepare("INSERT INTO users (firstname, lastname) VALUES (:first, :last)");
$stmt->execute([
    'last' => 'Stanyon',
    'first' => 'Chris',
]);

// with anonymous placeholders
$stmt = $db->prepare("INSERT INTO users (firstname, lastname) VALUES (?, ?)");
$stmt->execute([
    'Chris',
    'Stanyon',
]);

Open in new window

If you're trying to manage your code with AJAX, then I would suggest you remove that for now and get the script working with a standard form POST - this way you can see exactly what's going on. Once it's working, then re-introduce the AJAX call. The problem with trying to debug your server-side script while using AJAX is that the processes are happening in the background, so you won't always see what's happening.
Hi Chris, The code for insert_answers.php is at the end of the questionaire that's when it happens.  Looking over your suggestion now...I'll need a minute..adding it now.

The link you posted just has a form for registering - so it doesn't match the code you posted - the fields you have on that form don't match the fields you have in your code above, so I'm not sure what the relevance of that page link is - it has no relevance to the code you've posted.
It's actually in two parts.  The registration form works fine.  Once you hit submit that query runs.  Then the slider starts with the questions.  At the end of the slider that's when insert_answers.php runs.
Right - just ran through the registration process and the list of questions, and when I click the Submit button, I get this in the console:

Uncaught TypeError: document.tsexq.tsex is undefined
    submitAnswers https://audiodigz.com/Join-Us.php:1631
    onclick https://audiodigz.com/Join-Us.php:1

Open in new window

So you have a problem with your Javascript, not your PHP
Looking at your HTML, I'm guessing these 2 inputs should be named tsex, and NOT nolbgtq and yeslbgtq

<form class="questions" name="tsexq">
    <label></label><br>
    <input type="radio" id="nolbgtq" name="nolbgtq" value="nolbgtq">
    <label for="nolbgtq">No LBGTQ</label><br>
    <input type="radio" id="yeslbgtq" name="yeslbgtq" value="yeslbgtq">
    <label for="yeslbgtq">Yes LBGTQ</label><br>	
</form>

Open in new window

Here is what I have so far..Not sure what to put where your last name was...
try{
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
$client_id = $_REQUEST['client_id'];
try{
    $stmt = $db->prepare("INSERT INTO tbl_answers (client_id, 
        type,
      reasons,
        gender,
      on_gender,
        age, 
        sexual_orientation,
      on_sex,
        relationship,
        religious,
      on_religion,
        spiritual,
      on_spirit,
        therapy_before, 
        corona, 
        suicide, 
        panic, 
        medications, 
        pain,
        finances, 
        sleep,
        reference)) VALUES (:client_id, 
        :type,
      :reasons,
        :gender,
      :tgender,
        :age, 
        :sexual_orientation,
      :tsex,
        :relationship,
        :religious,
      :treligion,
        :spiritual,
      :tspirit,
        :therapy_before, 
        :corona, 
        :suicide, 
        :panic, 
        :medications, 
        :pain,
        :finances, 
        :sleep,
      :reference);
$stmt->execute([
    'type' =>.
   'reasons' =>,
    ' gender' =>,
   'tgender' =>,
    'age' =>, 
    'sexual_orientation'=>,
   'tsex'=>,
    'relationship'=>,
    'religious'=>,
   'treligion'=>,
    'spiritual'=>,
   'tspirit'=>,
    'therapy_before'=>, 
    'corona'=>, 
    'suicide'=>, 
    'panic'=>, 
    'medications'=>, 
    'pain'=>,
    'finances'=>, 
    'sleep'=>,
   'reference'=>,
]);

Open in new window

Okay.  I renamed those two fields.  I have not updated the PDO version of this code yet...still confused agout the last part..
$stmt->execute([
    'type' =>.
   'reasons' =>,
    ' gender' =>,
   'tgender' =>,
    'age' =>, 
    'sexual_orientation'=>,
   'tsex'=>,

Open in new window

The javascript..
<script>
$(function() {
   $('#registration').submit(function(){
        $.ajax({
          url: 'CLIENT/register_client.php',
          type: 'POST',
          data : $('#registration').serialize(),
        //   dataType : 'JSON',
          success: function(response){
                console.log(response);
                document.getElementById("client_id").value = response;
                $('#severalquestions').modal('show')
          }, error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                alert(msg);
            },
        });
        return false;
    });
});

    function submitAnswers() {
        var type = document.typeq.type.value;
      var reasons = document.reasonsq.reasons.value;
        var gender = document.genderq.gender.value;
      var tgender = document.tgenderq.tgender.value;
        var age = document.ageq.age.value;
        var sex = document.sexq.sex.value;
      var tsex = document.tsexq.tsex.value;
        var relationship = document.relationshipq.relationship.value;
        var religious = document.religiousq.religious.value;
      var treligious = document.treligiousq.treligious.value;
        var spiritual = document.spiritualq.spiritual.value;
      var tspiritual = document.tspiritualq.tspiritual.value;
        var counsel = document.counselq.counsel.value;
        var counsel1 = document.counsel1q.counsel1.value;
        var suicide = document.suicideq.suicide.value;
        var panic = document.panicq.panic.value;
        var medication = document.medicationq.medication.value;
        var pain = document.painq.pain.value;
        var finance = document.financeq.finance.value;
        var sleep = document.sleepq.sleep.value;
        var refer = document.referq.refer.value; 
        $('#severalquestions').modal('hide');
        
       $.ajax({
          url: 'CLIENT/insert_answers.php',
          type: 'POST',
          data : tmp,
          success: function(response){
                console.log(response);
                alert('Registration Successful!')
          }, error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                alert(msg);
            },
        });
        return false;
   }
</script> 


Open in new window

OK - so you've prepared a statement with named placeholders. You now need to pass an array into the execute method - the array needs to contain the keys that match your placeholder names along with the values, so you'd have something like this:

$stmt->execute([
    'client_id' => $client_id,
    'type' => $_REQUEST['type'], 
    'reasons' => $_REQUEST['reasons'],
    ' gender' => $_REQUEST['gender'],
    ...

Open in new window

Your submitAnswers() function looks a bit off. You set a lot of variables to the values of several forms, but then you do nothing with them - instead you submit data that's stored in a tmp variable, but I can't see where you're getting that from:

$.ajax({
    url: 'CLIENT/insert_answers.php',
    type: 'POST',
    data : tmp,
On it!

You are probably right about the javascript.  I did not write that so I am not sure where it is TMP..  Here is the code ready to post.  Should I get rid off all the REMS?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_REQUEST);

try{
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
$client_id = $_REQUEST['client_id'];
try{
    $stmt = $db->prepare("INSERT INTO tbl_answers (client_id, 
        type,
      reasons,
        gender,
      on_gender,
        age, 
        sexual_orientation,
      on_sex,
        relationship,
        religious,
      on_religion,
        spiritual,
      on_spirit,
        therapy_before, 
        corona, 
        suicide, 
        panic, 
        medications, 
        pain,
        finances, 
        sleep,
        reference)) VALUES (:client_id, 
        :type,
      :reasons,
        :gender,
      :tgender,
        :age, 
        :sexual_orientation,
      :tsex,
        :relationship,
        :religious,
      :treligion,
        :spiritual,
      :tspirit,
        :therapy_before, 
        :corona, 
        :suicide, 
        :panic, 
        :medications, 
        :pain,
        :finances, 
        :sleep,
      :reference);
$stmt->execute([
    'client_id' => $client_id,
    'type' => $_REQUEST['type'], 
    'reasons' => $_REQUEST['reasons'],
    'gender' => $_REQUEST['gender'],
   'tgender' => $_REQUEST['tgender'],
    'age' =>  $_REQUEST['age'],
    'sexual_orientation'=>$_REQUEST['sexual_orientation'],
   'tsex'=> $_REQUEST['tsex'],
    'relationship'=>$_REQUEST['relationship'],
    'religious'=> $_REQUEST['religious'],
   'treligion'=> $_REQUEST['treligion'],
    'spiritual'=> $_REQUEST['spiritual'],
   'tspirit'=> $_REQUEST['tspirit'],
    'therapy_before'=> $_REQUEST['therapy_before'], 
    'corona'=> $_REQUEST['corona'], 
    'suicide'=> $_REQUEST['suicide'], 
    'panic'=> $_REQUEST['panic'], 
    'medications'=>$_REQUEST['medications'], 
    'pain'=> $_REQUEST['pain'],
    'finances'=> $_REQUEST['finances'],
    'sleep'=> $_REQUEST['sleep'],
   'reference'=> $_REQUEST['reference'],
]);
   
   
   
   
   
   //$sql = "INSERT INTO `tbl_answers`(
        //`client_id`, 
        //`type`,
      //`reasons`,
        //`gender`,
      //`on_gender`,
        //`age`, 
        //`sexual_orientation`,
      //`on_sex`,
        //`relationship`,
        //`religious`,
      //`on_religion`,
        //`spiritual`,
      //`on_spirit`,
        //`therapy_before`, 
        //`corona`, 
        //`suicide`, 
        //`panic`, 
        //`medications`, 
        //`pain`,
        //`finances`, 
        //`sleep`,
        //`reference`) VALUES ( '" .
        //$client_id . "', '" .
        //$_REQUEST['type'] . "', '" .
        //$_REQUEST['reasons'] . "', '" .
      //$_REQUEST['gender'] . "', '" .
      //$_REQUEST['tgender'] . "', '" .
        //$_REQUEST['age'] . "', '" .
        //$_REQUEST['sex'] . "', '" .
      //$_REQUEST['tsex'] . "', '" .
        //$_REQUEST['relationship'] . "', '" .
        //$_REQUEST['religious'] . "', '" .
      //$_REQUEST['treligious'] . "', '" .
       // $_REQUEST['spiritual'] . "', '" .
      //$_REQUEST['tspiritual'] . "', '" .
        //$_REQUEST['counsel'] . "', '" .
        //$_REQUEST['counsel1'] . "', '" .
        //$_REQUEST['suicide'] . "', '" .
        //$_REQUEST['panic'] . "', '" .
        //$_REQUEST['medication'] . "', '" .
        //$_REQUEST['pain'] . "', '" .
        //$_REQUEST['finance'] . "', '" .
        //$_REQUEST['sleep'] . "', '" .
        //$_REQUEST['refer'] . "'
    //)";
    if ($stmt = $pdo->prepare($sql)) {
        // $data = [
        //     'name' => $_REQUEST['name'],
        //     'street_number' => $_REQUEST['street_number'],
        //     'street' => $_REQUEST['street'],
        //     'city' => $_REQUEST['city'],
        //     'state' => $_REQUEST['state'],
        //     'zip_code' => $_REQUEST['zip_code'],
        //     'country' => $_REQUEST['country'],
        //     'email' => $_REQUEST['email'],
        // ];
    
        // $stmt->execute($data);
        $stmt->execute();
        $id = $pdo->lastInsertId();
    
        //var_dump($sql, $data, $id);
        
        echo "Record inserted successfully";
    
    } else {
        die("Could not prepare Statement");
    }
}catch(Exception $e){
    echo $e->getMessage();
}
?>

Open in new window

Did this to tsex
<!--LGBTQ Start---------------------------------------------------->
            <li><span style="font-weight: bold;">Do you prefer an LGBTQ therapist?</span><br>
             <form class="questions" name="tsexq">
                <label></label><br>
              <input type="radio" id="nolbgtq" name="tsexq" value="nolbgtq">
              <label for="nolbgtq">No LBGTQ</label><br>
            <input type="radio" id="yeslbgtq" name="tsexq" value="yeslbgtq">
              <label for="yeslbgtq">Yes LBGTQ</label><br>   
            </form>
             </li>   
            <!--LGBTQ End-------------------------------------------------------->

Open in new window

Yeah - clean up the code. What you should end up with is something like this:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

try {
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("ERROR: Could not connect. " . $e->getMessage());
}

try {
 
    $client_id = $_REQUEST['client_id'];

    $stmt = $pdo->prepare("INSERT INTO tbl_answers (client_id, 
        ...
        ...
    ");

    $stmt->execute([
        'client_id' => $client_id,
        'type' => $_REQUEST['type'],
        ... 
    ]);

    echo "Record inserted successfully";

} catch(Exception $e) {
    die($e->getMessage());
}

Open in new window

Bear in mind that in your code, you've named your DB connection as $pdo, but then later on you try and use $db !!
If you look at the error that you're getting in the console, you'll see this:

document.tsexq.tsex is undefined

So you JS is looking for a element called tsex within an element called tsexq. Your form is called tsexq, so the checkboxes should be called tsex:

<input type="radio" id="nolbgtq" name="tsex" value="nolbgtq">
<input type="radio" id="yeslbgtq" name="tsex" value="yeslbgtq">

Open in new window

I know we've discussed this before, but I'll reiterate to stress the point - you should build your app piece by piece - at the moment you have several problems with all parts of your code - the HTML isn't working, the Javascript is wrong and your server-side PHP code is flawed. Work on each of these parts one at a time, and make steady progress. If you HTML isn't correct, your JS will never work, and if your JS doesn't work, your PHP will never work.
HTML corrected....
This is cleaner but still doesn't look right.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_REQUEST);

try{
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
$client_id = $_REQUEST['client_id'];
try{
    $stmt = $db->prepare("INSERT INTO tbl_answers (client_id, 
        type,
      reasons,
        gender,
      on_gender,
        age, 
        sexual_orientation,
      on_sex,
        relationship,
        religious,
      on_religion,
        spiritual,
      on_spirit,
        therapy_before, 
        corona, 
        suicide, 
        panic, 
        medications, 
        pain,
        finances, 
        sleep,
        reference)) VALUES (:client_id, 
        :type,
      :reasons,
        :gender,
      :tgender,
        :age, 
        :sexual_orientation,
      :tsex,
        :relationship,
        :religious,
      :treligion,
        :spiritual,
      :tspirit,
        :therapy_before, 
        :corona, 
        :suicide, 
        :panic, 
        :medications, 
        :pain,
        :finances, 
        :sleep,
      :reference);
$stmt->execute([
    'client_id' => $client_id,
    'type' => $_REQUEST['type'], 
    'reasons' => $_REQUEST['reasons'],
    'gender' => $_REQUEST['gender'],
   'tgender' => $_REQUEST['tgender'],
    'age' =>  $_REQUEST['age'],
    'sexual_orientation'=>$_REQUEST['sexual_orientation'],
   'tsex'=> $_REQUEST['tsex'],
    'relationship'=>$_REQUEST['relationship'],
    'religious'=> $_REQUEST['religious'],
   'treligion'=> $_REQUEST['treligion'],
    'spiritual'=> $_REQUEST['spiritual'],
   'tspirit'=> $_REQUEST['tspirit'],
    'therapy_before'=> $_REQUEST['therapy_before'], 
    'corona'=> $_REQUEST['corona'], 
    'suicide'=> $_REQUEST['suicide'], 
    'panic'=> $_REQUEST['panic'], 
    'medications'=>$_REQUEST['medications'], 
    'pain'=> $_REQUEST['pain'],
    'finances'=> $_REQUEST['finances'],
    'sleep'=> $_REQUEST['sleep'],
   'reference'=> $_REQUEST['reference'],
]);
   
    if ($stmt = $pdo->prepare($sql)) {
        $stmt->execute();
        $id = $pdo->lastInsertId();
                 
        echo "Record inserted successfully";
    
    } else {
        die("Could not prepare Statement");
    }
}catch(Exception $e){
    echo $e->getMessage();
}
?>

Open in new window

fixed..$stmt = $pdo->prepare("INSERT INTO tbl_answers (client_id, 
Found the error  It was an "

User generated image
Should I load it up to the server?
Nope - re-read my previous code - as you have it, you're preparing and executing twice, and you're still trying to use $db when your connection is called $pdo
You can try loading it up on the server, but you haven't fixed your Javascript, then it won't work. You need to make sure you're actually submitting the correct data in your AJAX call. Unless you've changed it, all you're currently doing is sending an empty variable called tmp
Do you mean the lastinsertID part?  Other things fixed.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_REQUEST);

try{
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
$client_id = $_REQUEST['client_id'];
try{
    $stmt = $pdo->prepare("INSERT INTO tbl_answers (client_id, 
        type,
      reasons,
        gender,
      on_gender,
        age, 
        sexual_orientation,
      on_sex,
        relationship,
        religious,
      on_religion,
        spiritual,
      on_spirit,
        therapy_before, 
        corona, 
        suicide, 
        panic, 
        medications, 
        pain,
        finances, 
        sleep,
        reference)) VALUES (:client_id, 
        :type,
      :reasons,
        :gender,
      :tgender,
        :age, 
        :sexual_orientation,
      :tsex,
        :relationship,
        :religious,
      :treligion,
        :spiritual,
      :tspirit,
        :therapy_before, 
        :corona, 
        :suicide, 
        :panic, 
        :medications, 
        :pain,
        :finances, 
        :sleep,
      :reference");
$stmt->execute([
    'client_id' => $client_id,
   'type' => $_REQUEST['type'], 
    'reasons' => $_REQUEST['reasons'],
    'gender' => $_REQUEST['gender'],
   'tgender' => $_REQUEST['tgender'],
    'age' =>  $_REQUEST['age'],
    'sexual_orientation'=>$_REQUEST['sexual_orientation'],
   'tsex'=> $_REQUEST['tsex'],
    'relationship'=>$_REQUEST['relationship'],
    'religious'=> $_REQUEST['religious'],
   'treligion'=> $_REQUEST['treligion'],
    'spiritual'=> $_REQUEST['spiritual'],
   'tspirit'=> $_REQUEST['tspirit'],
    'therapy_before'=> $_REQUEST['therapy_before'], 
    'corona'=> $_REQUEST['corona'], 
    'suicide'=> $_REQUEST['suicide'], 
    'panic'=> $_REQUEST['panic'], 
    'medications'=>$_REQUEST['medications'], 
    'pain'=> $_REQUEST['pain'],
    'finances'=> $_REQUEST['finances'],
    'sleep'=> $_REQUEST['sleep'],
   'reference'=> $_REQUEST['reference'],
]);
   
    if ($stmt = $pdo->prepare($sql)) {
        $stmt->execute();
        $id = $pdo->lastInsertId();
                 
        echo "Record inserted successfully";
    
    } else {
        die("Could not prepare Statement");
    }
}catch(Exception $e){
    echo $e->getMessage();
}
?>

Open in new window


No - you're preparing the statement on line 15 and then executing it on line 58. That's fine, but then you go on to try and prepare and execute another statement on lines 83 and 84 !

Have another look at the code I provided and you'll see that we prepare the statement and execute it once:

try {
 
    $client_id = $_REQUEST['client_id'];

    $stmt = $pdo->prepare("INSERT INTO tbl_answers (client_id, 
        ...
        ...
    ");

    $stmt->execute([
        'client_id' => $client_id,
        'type' => $_REQUEST['type'],
        ... 
    ]);

    echo "Record inserted successfully";

} catch(Exception $e) {
    die($e->getMessage());
}

Open in new window

Like this?
'spiritual'=> $_REQUEST['spiritual'],
   'tspirit'=> $_REQUEST['tspirit'],
    'therapy_before'=> $_REQUEST['therapy_before'], 
    'corona'=> $_REQUEST['corona'], 
    'suicide'=> $_REQUEST['suicide'], 
    'panic'=> $_REQUEST['panic'], 
    'medications'=>$_REQUEST['medications'], 
    'pain'=> $_REQUEST['pain'],
    'finances'=> $_REQUEST['finances'],
    'sleep'=> $_REQUEST['sleep'],
   'reference'=> $_REQUEST['reference'],
]);
   echo "Record inserted successfully";

} catch(Exception $e) {
    die($e->getMessage());
}
?>

Open in new window

Okay uploading! :)
Now do I need to add fields where it says TMP in the javascript?
Yeah - you need to make sure your JS function is sending the right data in it's AJAX request. Easiest way to do this would be to create an object with properties matching what you need in the PHP along with the values, so something like this:

function submitAnswers() {

    let dataObject = {
        'type' : document.typeq.type.value,
        'reasons' : document.reasonsq.reasons.value,
        'gender' : document.genderq.gender.value,
        ...
    }
    
    $('#severalquestions').modal('hide');

    $.ajax({
        url: 'CLIENT/insert_answers.php',
        type: 'POST',
        data : dataObject,
        success: function(response) {
            ...

Open in new window

We create an object called dataObject. It has properties that will be available in the $_REQUEST (or $_POST) arrays. We then send that across as the data argument to the AJAX request
Thank you. Okay on it.
Okay how does this look?
function submitAnswers() {
    let dataObject = {
        'type' : document.typeq.type.value,
        'reasons' : document.reasonsq.reasons.value,
        'gender' : document.genderq.gender.value,
      'type' : document.typeq.type.value,
      'reasons' : document.reasonsq.reasons.value,
        'gender' : document.genderq.gender.value,
      'tgender' : document.tgenderq.tgender.value,
        'age' : document.ageq.age.value,
        'sex' : document.sexq.sex.value,
      'tsex' : document.tsexq.tsex.value,
        'relationship': document.relationshipq.relationship.value,
        'religious': document.religiousq.religious.value,
      'treligious' : document.treligiousq.treligious.value,
        'spiritual' : document.spiritualq.spiritual.value,
      'tspiritual' : document.tspiritualq.tspiritual.value,
        'counsel' : document.counselq.counsel.value,
        'counsel1' : document.counsel1q.counsel1.value,
        'suicide' : document.suicideq.suicide.value,
        'panic' : document.panicq.panic.value,
        'medication' : document.medicationq.medication.value,
        'pain' : document.painq.pain.value,
        'finance' : document.financeq.finance.value,
        'sleep' : document.sleepq.sleep.value,
        'refer' : document.referq.refer.value,
    }
    
    $('#severalquestions').modal('hide');

    $.ajax({
        url: 'CLIENT/insert_answers.php',
        type: 'POST',
        data : dataObject,
        success: function(response) {
                console.log(response);
                alert('Registration Successful!')
          }, error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                alert(msg);
            },
        });
        return false;
   }

Open in new window

Yeah - looks good, but based on your PHP script, aren't you also expecting the client_id in the POST data ??
Yes I am.  That would come from the registration of the client earlier..Like this?
 let dataObject = {
        'client_id' : document.client_id.client_id.value,
      'type' : document.typeq.type.value,
        'reasons' : document.reasonsq.reasons.value,

Open in new window

I removed the client-id and it all worked except for the insertion of the new record into tbl_answers.

OK - so you need to check the network tab of your WebTools. Click your Submit button and then check the response on the AJAX request to see if you're getting any errors
Here you go..
User generated image
Got back a lot of info this time...
array(33) {
  ["type"]=>
  string(10) "Individual"
  ["reasons"]=>
  string(9) "Addiction"
  ["gender"]=>
  string(4) "male"
  ["tgender"]=>
  string(2) "DM"
  ["age"]=>
  string(2) "18"
  ["sex"]=>
  string(8) "straight"
  ["tsex"]=>
  string(7) "nolbgtq"
  ["relationship"]=>
  string(6) "single"
  ["religious"]=>
  string(3) "yes"
  ["treligious"]=>
  string(2) "No"
  ["spiritual"]=>
  string(3) "yes"
  ["tspiritual"]=>
  string(3) "yes"
  ["counsel"]=>
  string(3) "yes"
  ["counsel1"]=>
  string(3) "yes"
  ["suicide"]=>
  string(5) "never"
  ["panic"]=>
  string(3) "yes"
  ["medication"]=>
  string(3) "yes"
  ["pain"]=>
  string(3) "yes"
  ["finance"]=>
  string(4) "good"
  ["sleep"]=>
  string(4) "good"
  ["refer"]=>
  string(5) "radio"
  ["_policy"]=>
  string(55) "{"restricted_market":true,"tracking_market":"explicit"}"
  ["visitor"]=>
  string(40) "vid=3af5623c-fbfc-576b-93fc-6a3b00146591"
  ["pwinteraction"]=>
  string(29) "Thu, 13 Aug 2020 19:43:16 GMT"
  ["_ga"]=>
  string(27) "GA1.2.2139472567.1597347797"
  ["_gcl_au"]=>
  string(25) "1.1.2084690340.1597402826"
  ["sb-updates"]=>
  string(5) "3.0.8"
  ["phpbb3_amhyp_u"]=>
  string(1) "1"
  ["phpbb3_amhyp_k"]=>
  string(0) ""
  ["phpbb3_amhyp_sid"]=>
  string(32) "932f20f213334320f7601d29862ad1ab"
  ["OPTOUTMULTI"]=>
  string(18) "0:0|c3:0|c2:0|c4:0"
  ["utag_main"]=>
  string(163) "v_id:0173e958f5a40002530a31c95dd503073006f06b007e8$_sn:3$_ss:0$_st:1599167305915$ses_id:1599165503045;exp-session$_pn:2;exp-session$isc:undefined;exp-1599169103066"
  ["PHPSESSID"]=>
  string(32) "2db7ab1be59e059937df8f14f24c349c"
}
<br />
<b>Notice</b>:  Undefined index: client_id in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>13</b><br />
<br />
<b>Notice</b>:  Undefined index: sexual_orientation in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>65</b><br />
<br />
<b>Notice</b>:  Undefined index: tspirit in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>71</b><br />
<br />
<b>Notice</b>:  Undefined index: therapy_before in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>72</b><br />
<br />
<b>Notice</b>:  Undefined index: corona in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>73</b><br />
<br />
<b>Notice</b>:  Undefined index: medications in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>76</b><br />
<br />
<b>Notice</b>:  Undefined index: finances in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>78</b><br />
<br />
<b>Notice</b>:  Undefined index: reference in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>80</b><br />
SQLSTATE[42000]: Syntax error or access violation: 1064 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 ') VALUES (NULL, 
        'Individual',
      'Addiction',
        'male',
      'DM',
  ' at line 22

Open in new window

Better...but. Still a few
array(33) {
  ["type"]=>
  string(10) "Individual"
  ["reasons"]=>
  string(9) "Addiction"
  ["gender"]=>
  string(4) "male"
  ["tgender"]=>
  string(2) "DM"
  ["age"]=>
  string(2) "18"
  ["sex"]=>
  string(8) "straight"
  ["tsex"]=>
  string(7) "nolbgtq"
  ["relationship"]=>
  string(6) "single"
  ["religious"]=>
  string(3) "yes"
  ["treligious"]=>
  string(2) "No"
  ["spiritual"]=>
  string(3) "yes"
  ["tspiritual"]=>
  string(3) "yes"
  ["counsel"]=>
  string(3) "yes"
  ["counsel1"]=>
  string(3) "yes"
  ["suicide"]=>
  string(5) "never"
  ["panic"]=>
  string(3) "yes"
  ["medication"]=>
  string(3) "yes"
  ["pain"]=>
  string(3) "yes"
  ["finance"]=>
  string(4) "good"
  ["sleep"]=>
  string(4) "good"
  ["refer"]=>
  string(5) "radio"
  ["_policy"]=>
  string(55) "{"restricted_market":true,"tracking_market":"explicit"}"
  ["visitor"]=>
  string(40) "vid=3af5623c-fbfc-576b-93fc-6a3b00146591"
  ["pwinteraction"]=>
  string(29) "Thu, 13 Aug 2020 19:43:16 GMT"
  ["_ga"]=>
  string(27) "GA1.2.2139472567.1597347797"
  ["_gcl_au"]=>
  string(25) "1.1.2084690340.1597402826"
  ["sb-updates"]=>
  string(5) "3.0.8"
  ["phpbb3_amhyp_u"]=>
  string(1) "1"
  ["phpbb3_amhyp_k"]=>
  string(0) ""
  ["phpbb3_amhyp_sid"]=>
  string(32) "932f20f213334320f7601d29862ad1ab"
  ["OPTOUTMULTI"]=>
  string(18) "0:0|c3:0|c2:0|c4:0"
  ["utag_main"]=>
  string(163) "v_id:0173e958f5a40002530a31c95dd503073006f06b007e8$_sn:3$_ss:0$_st:1599167305915$ses_id:1599165503045;exp-session$_pn:2;exp-session$isc:undefined;exp-1599169103066"
  ["PHPSESSID"]=>
  string(32) "2db7ab1be59e059937df8f14f24c349c"
}
<br />
<b>Notice</b>:  Undefined index: client_id in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>13</b><br />
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Open in new window

OK. So you've got a couple of problems. The undefined index errors are because you're not passing in the right info to your AJAX request - the dataObject doesn't contain the keys : client_id, sexual_orientation, tspirit, therapy_before etc.

The other error indicates you've got a problem in your SQL statement, so you need to double check that.
Right - you're now not passing in the client_id to your AJAX request, so you need to sort that.

The invalid parameter number is caused by passing in a different amount of values to your execute() method than the number of placeholders in your SQL
Ok, So how doI get that client_id as it was just created so to speak..I believe earlier there was something about last id in the insert-answers.php...Okay found an error in Javascript  should be 22 fields.  It is now.  Let me test.
Still not there...
array(33) {
  ["type"]=>
  string(10) "Individual"
  ["reasons"]=>
  string(9) "Addiction"
  ["gender"]=>
  string(4) "male"
  ["tgender"]=>
  string(2) "DM"
  ["age"]=>
  string(2) "18"
  ["sex"]=>
  string(8) "straight"
  ["tsex"]=>
  string(7) "nolbgtq"
  ["relationship"]=>
  string(6) "single"
  ["religious"]=>
  string(3) "yes"
  ["treligious"]=>
  string(2) "No"
  ["spiritual"]=>
  string(3) "yes"
  ["tspiritual"]=>
  string(3) "yes"
  ["counsel"]=>
  string(3) "yes"
  ["counsel1"]=>
  string(3) "yes"
  ["suicide"]=>
  string(5) "never"
  ["panic"]=>
  string(3) "yes"
  ["medication"]=>
  string(3) "yes"
  ["pain"]=>
  string(3) "yes"
  ["finance"]=>
  string(4) "good"
  ["sleep"]=>
  string(4) "good"
  ["refer"]=>
  string(5) "radio"
  ["_policy"]=>
  string(55) "{"restricted_market":true,"tracking_market":"explicit"}"
  ["visitor"]=>
  string(40) "vid=3af5623c-fbfc-576b-93fc-6a3b00146591"
  ["pwinteraction"]=>
  string(29) "Thu, 13 Aug 2020 19:43:16 GMT"
  ["_ga"]=>
  string(27) "GA1.2.2139472567.1597347797"
  ["_gcl_au"]=>
  string(25) "1.1.2084690340.1597402826"
  ["sb-updates"]=>
  string(5) "3.0.8"
  ["phpbb3_amhyp_u"]=>
  string(1) "1"
  ["phpbb3_amhyp_k"]=>
  string(0) ""
  ["phpbb3_amhyp_sid"]=>
  string(32) "932f20f213334320f7601d29862ad1ab"
  ["OPTOUTMULTI"]=>
  string(18) "0:0|c3:0|c2:0|c4:0"
  ["utag_main"]=>
  string(163) "v_id:0173e958f5a40002530a31c95dd503073006f06b007e8$_sn:3$_ss:0$_st:1599167305915$ses_id:1599165503045;exp-session$_pn:2;exp-session$isc:undefined;exp-1599169103066"
  ["PHPSESSID"]=>
  string(32) "2db7ab1be59e059937df8f14f24c349c"
}
<br />
<b>Notice</b>:  Undefined index: client_id in <b>/home/audiodigz/public_html/CLIENT/insert-answers.php</b> on line <b>13</b><br />
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Open in new window

Could this be needed?

$id = $pdo->lastInsertId();

Open in new window

No - your client ID comes from the registration form. When you submit that, you make an AJAX request to CLIENT/register_client.php. You then retrieve the Client ID from that response, and set the value of the #client_id element:

document.getElementById("client_id").value = response;

So you already have the client id in your page. You just need to pass that into the new AJAX request as a property of the dataObject. Something like this maybe:

let dataObject = {
    'client_id' : $('#client_id').val(),
    'type' : document.typeq.type.value,
    'reasons' : document.reasonsq.reasons.value,
    ...
}

Open in new window

My oh my...line 1657 join-us.php
array(34) {
  ["client_id"]=>
  string(3) "151"
  ["type"]=>
  string(10) "Individual"
  ["reasons"]=>
  string(9) "Addiction"
  ["gender"]=>
  string(4) "male"
  ["tgender"]=>
  string(2) "DM"
  ["age"]=>
  string(2) "18"
  ["sex"]=>
  string(8) "straight"
  ["tsex"]=>
  string(7) "nolbgtq"
  ["relationship"]=>
  string(6) "single"
  ["religious"]=>
  string(3) "yes"
  ["treligious"]=>
  string(2) "No"
  ["spiritual"]=>
  string(3) "yes"
  ["tspiritual"]=>
  string(3) "yes"
  ["counsel"]=>
  string(3) "yes"
  ["counsel1"]=>
  string(3) "yes"
  ["suicide"]=>
  string(5) "never"
  ["panic"]=>
  string(3) "yes"
  ["medication"]=>
  string(3) "yes"
  ["pain"]=>
  string(3) "yes"
  ["finance"]=>
  string(4) "good"
  ["sleep"]=>
  string(4) "good"
  ["refer"]=>
  string(5) "radio"
  ["_policy"]=>
  string(55) "{"restricted_market":true,"tracking_market":"explicit"}"
  ["visitor"]=>
  string(40) "vid=3af5623c-fbfc-576b-93fc-6a3b00146591"
  ["pwinteraction"]=>
  string(29) "Thu, 13 Aug 2020 19:43:16 GMT"
  ["_ga"]=>
  string(27) "GA1.2.2139472567.1597347797"
  ["_gcl_au"]=>
  string(25) "1.1.2084690340.1597402826"
  ["sb-updates"]=>
  string(5) "3.0.8"
  ["phpbb3_amhyp_u"]=>
  string(1) "1"
  ["phpbb3_amhyp_k"]=>
  string(0) ""
  ["phpbb3_amhyp_sid"]=>
  string(32) "932f20f213334320f7601d29862ad1ab"
  ["OPTOUTMULTI"]=>
  string(18) "0:0|c3:0|c2:0|c4:0"
  ["utag_main"]=>
  string(163) "v_id:0173e958f5a40002530a31c95dd503073006f06b007e8$_sn:3$_ss:0$_st:1599167305915$ses_id:1599165503045;exp-session$_pn:2;exp-session$isc:undefined;exp-1599169103066"
  ["PHPSESSID"]=>
  string(32) "2db7ab1be59e059937df8f14f24c349c"
}
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Open in new window

success: function(response) {
                console.log(response);
                alert('Registration Successful!')
          }, error: function (jqXHR, exception) {

Open in new window

Like I said, the Invalid Parameter Number means that you're not passing the right amount of values into the execute() method. The placeholders in your SQL are the bits that are prefixed with the colon. You need to pass exactly the same amount of key/value pairs into the execute method

// the SQL has 3 placeholder named val1, val2, val3
$stmt = $pdo->prepare("INSERT INTO someTable (col1, col2, col3) VALUES (:val1, :val2, :val3)");

// the array needs exactly 3 key/value pairs, and the keys names HAVE to match the placeholder names
$stmt->execute([
    'val1' => 'xxxx',
    'val2' => 'xxxx',
    'val3' => 'xxxx',
]);

Open in new window

Hi Chris I just counted the rows/fields again.  Everything is set at 22.
Post up your PHP file and I'll take another look
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_REQUEST);

try{
    $pdo = new PDO("mysql:host=localhost;dbname=", "", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
$client_id = $_REQUEST['client_id'];
try{
    $stmt = $pdo->prepare("INSERT INTO tbl_answers (client_id, 
        type,
      reasons,
        gender,
      on_gender,
        age, 
        sexual_orientation,
      on_sex,
        relationship,
        religious,
      on_religious,
        spiritual,
      on_spirit,
        therapy_before, 
        corona, 
        suicide, 
        panic, 
        medications, 
        pain,
        finances, 
        sleep,
        reference)) VALUES (:client_id, 
        :type,
      :reasons,
        :gender,
      :tgender,
        :age, 
        :sex,
      :tsex,
        :relationship,
        :religious,
      :treligious,
        :spiritual,
      :tspiritual,
        :counsel, 
        :counsel1, 
        :suicide, 
        :panic, 
        :medication, 
        :pain,
        :finance, 
        :sleep,
      :refer");
$stmt->execute([
    'client_id' => $_REQUEST['client_id'],
   'type' => $_REQUEST['type'], 
    'reasons' => $_REQUEST['reasons'],
    'gender' => $_REQUEST['gender'],
   'tgender' => $_REQUEST['tgender'],
    'age' =>  $_REQUEST['age'],
    'sex'=>$_REQUEST['sex'],
   'tsex'=> $_REQUEST['tsex'],
    'relationship'=>$_REQUEST['relationship'],
    'religious'=> $_REQUEST['religious'],
   'treligious'=> $_REQUEST['treligious'],
    'spiritual'=> $_REQUEST['spiritual'],
   'tspiritual'=> $_REQUEST['tspiritual'],
    'counsel'=> $_REQUEST['counsel'], 
    'counsel1'=> $_REQUEST['counsel1'], 
    'suicide'=> $_REQUEST['suicide'], 
    'panic'=> $_REQUEST['panic'], 
    'medication'=>$_REQUEST['medication'], 
    'pain'=> $_REQUEST['pain'],
    'finance'=> $_REQUEST['finance'],
    'sleep'=> $_REQUEST['sleep'],
   'refer'=> $_REQUEST['refer'],
]);
   echo "Record inserted successfully";

} catch(Exception $e) {
    die($e->getMessage());
} 
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Okay made the changes and fixed the data length in the table as well.
array(34) {
  ["client_id"]=>
  string(3) "155"
  ["type"]=>
  string(10) "Individual"
  ["reasons"]=>
  string(9) "Addiction"
  ["gender"]=>
  string(4) "male"
  ["tgender"]=>
  string(4) "Male"
  ["age"]=>
  string(2) "19"
  ["sex"]=>
  string(8) "straight"
  ["tsex"]=>
  string(7) "nolbgtq"
  ["relationship"]=>
  string(6) "single"
  ["religious"]=>
  string(3) "yes"
  ["treligious"]=>
  string(2) "No"
  ["spiritual"]=>
  string(3) "yes"
  ["tspiritual"]=>
  string(3) "yes"
  ["counsel"]=>
  string(3) "yes"
  ["counsel1"]=>
  string(3) "yes"
  ["suicide"]=>
  string(5) "never"
  ["panic"]=>
  string(3) "yes"
  ["medication"]=>
  string(3) "yes"
  ["pain"]=>
  string(3) "yes"
  ["finance"]=>
  string(4) "good"
  ["sleep"]=>
  string(4) "good"
  ["refer"]=>
  string(5) "radio"
  ["_policy"]=>
  string(55) "{"restricted_market":true,"tracking_market":"explicit"}"
  ["visitor"]=>
  string(40) "vid=3af5623c-fbfc-576b-93fc-6a3b00146591"
  ["pwinteraction"]=>
  string(29) "Thu, 13 Aug 2020 19:43:16 GMT"
  ["_ga"]=>
  string(27) "GA1.2.2139472567.1597347797"
  ["_gcl_au"]=>
  string(25) "1.1.2084690340.1597402826"
  ["sb-updates"]=>
  string(5) "3.0.8"
  ["phpbb3_amhyp_u"]=>
  string(1) "1"
  ["phpbb3_amhyp_k"]=>
  string(0) ""
  ["phpbb3_amhyp_sid"]=>
  string(32) "932f20f213334320f7601d29862ad1ab"
  ["OPTOUTMULTI"]=>
  string(18) "0:0|c3:0|c2:0|c4:0"
  ["utag_main"]=>
  string(163) "v_id:0173e958f5a40002530a31c95dd503073006f06b007e8$_sn:3$_ss:0$_st:1599167305915$ses_id:1599165503045;exp-session$_pn:2;exp-session$isc:undefined;exp-1599169103066"
  ["PHPSESSID"]=>
  string(32) "2db7ab1be59e059937df8f14f24c349c"
}
SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'on_gender' at row 1
jquery-3.3.1.slim.min.js:2 [Violation] 'load' handler took 70206ms

Open in new window

OK - so you've fixed the data length, so are you now NOT getting any errors from your PHP script?
Had to screen shot this!!!!!!!!

User generated image

It works!  Record inserted!!!!!!
Yesssss !!

Nice one David :)
Nice one Chris!  What a challenge!  You did it! Again!!!!!!  Thankyou so much!
You're welcome :)

You've certainly gone the 'long way round' to get there, and made it way more difficult for yourself that it needed be. You've effectively done everything backwards, which is why you had so many problems.

Moving forward, I would strongly suggest you completely forget about AJAX until the very end. First step - get your HTML right. Second, make sure your PHP script is capable of handling POST data (start using POST instead of REQUEST / do a simple var_dump so you can visualise what you're receiving). Then make sure it can run your DB queries (even if you hardcode values in). Only after you've got that lot sorted should you even consider moving on to the JS/AJAX stuff. Build you application piece by piece - if you throw everything at it in one go, then you're constantly fighting a logical approach, and debugging becomes a nightmare - you never know which part (probably all) is failing.

Good luck with the rest of your project
I think this is the first time ever that I've had 3 continuous pages of email notifications about a question. :)
Thank you everyone.  Advice is well taken.