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

asked on

Inserting Values Into a table

This is my query...
"INSERT INTO tbl_set_times (therapist_id, time_id, date, available)  " & _
    "VALUES (""" & $therapist & """, """ & SD & """, """ & ckb & """,)"

Open in new window

I know this has a way to go...
First the date is displayed as Thursday, September 10, 2020  should it also be stored that way?
<input id="SD" type="text" name="mysched" value="Session Date" readonly/>

Open in new window

Second there is a series of 15 check boxes.  I imagine that I would have to cycle through them somehow.
Thirdthis is how the check boxes are set up on the form
<form name=checktimes method="post" action="check.php">  
<!--fieldset-->  
<label><strong>Morning Sessions</strong></label><br>
   <input type="checkbox" name="ckb" value="1" onclick="chkcontrol(0)">&nbsp;7:00 am to 8:00 am<br>  
   <input type="checkbox" name="ckb" value="2" onclick="chkcontrol(1)">&nbsp;8:00 am to 9:00 am<br>  
   <input type="checkbox" name="ckb" value="3" onclick="chkcontrol(2)">&nbsp;9:00 am to 10:00 am<br>
   <input type="checkbox" name="ckb" value="4" onclick="chkcontrol(3)">&nbsp;10:00 am to 11:00 am<br>
   <input type="checkbox" name="ckb" value="5" onclick="chkcontrol(4)">&nbsp;11:00 am to 12:00 pm<br>
<br><label><strong>Afternoon Sessions</strong></label><br>
   <input type="checkbox" name="ckb" value="6" onclick="chkcontrol(5)">&nbsp;12:00 pm to 1:00 pm<br>
   <input type="checkbox" name="ckb" value="7" onclick="chkcontrol(6);">&nbsp;1:00 pm to 2:00 pm<br> 

Open in new window

Fourth therapist is pulled from a variable on the page
Any help on this complicated query is appreciated.  Thank you.
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Normally you would give an array the name with square brackets

"ckb[]"

to make it appear as an array on the server:

$ckbs = $_POST['ckb'];
foreach( $ckbs as $ckb => $n ) {
  print "$n ".$ckbs[$ckb]."\n";
}

Open in new window

Hey David,

If the column type in your DB table is set to date, then you should enter it as yyyy-mm-dd, for example 2020-03-27

As Michel mentioned, change the names of your checkboxes to an array - ckb[]. This will allow more than one checkbox to be selected. You haven't said how you want to handle multiple selections (several boxes ticked) at the DB level (one record with all selected values concatenated or one record for each checkbox selected), so you'll need to clarify that. And remember - only checkboxes that are ticked are sent to the server.

You really need to be using a prepared statement for this, as we've spoken about before. This will save your site from SQL Injection attacks and clean up your code. Simplified PDO example:

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

$stmt->execute([
    $therpistId,
    $timeId,
    $date,
    $available,
]);

Open in new window

Have you swtiched over to PDO yet, or are you still using MySQLi (it's easier to do with PDO!)

FYI - your SQL statement appears to have 4 columns but only 3 values, so it's likely to fail.
Avatar of David Schure
David Schure

ASKER

Thank you Chtis. using PDO going forward,  I have someone helping in the conversion.  I would need each record separately...


User generated image

and this is the table...
User generated image
Excellent on the PDO conversion :)

Right - for the separate records, you'd need to name your checkboxes like we suggested above and then loop through them - running the execute() method inside the loop:

$therapistId = 123;
$date = '2020-05-27';
$available = true;

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date,
        $available,
    ]);
}

Open in new window

Coming back as Warning: Invalid argument supplied for foreach() in /home/audiodigz/public_html/THERAPIST/check.php on line 16 
foreach ($_POST['ckb'] as $timeId) {

Open in new window

did this on the check boxes
<label><strong>Morning Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="1" onclick="chkcontrol(0)">&nbsp;7:00 am to 8:00 am<br>  
   <input type="checkbox" name="ckb[]" value="2" onclick="chkcontrol(1)">&nbsp;8:00 am to 9:00 am<br>  
   <input type="checkbox" name="ckb[]" value="3" onclick="chkcontrol(2)">&nbsp;9:00 am to 10:00 a

Open in new window

Hmmm - it all looks good. That error indicates that the post array doesn't have a ckb index. This can be caused by NOT selecting any tickboxes.

As a sanity check, dump out the POST array at the start of your script to see what you're getting back:

var_dump($_POST);

Open in new window

Getting this back.
array(1) { ["ckb"]=> string(1) "4" }
Warning: Invalid argument supplied for foreach() in /home/audiodigz/public_html/THERAPIST/check.php on line 16 
I cheked 4 boxes off
Right - for some reason, your POST data is seeing a single ckb element, so it's not an array and therefore the foreach is failing (argument not valid). It's also not seeing the Date info, so I'm guessing your HTML is off somewhere - maybe not wrapping everying in the correct <form> element ??

The HTML you posted for your checkboxes is correct, but something else must be going on because you're script is not seeing that data.

I notice you have some Javascript on the Checkboxes, so it's possible that's interferring with it.
I will disable the javascript for now

<div id="datepicker"></div>
   <input id="SD" type="text" name="mysched" value="Session Date" readonly/>
   <div id="times">
   

<form name=checktimes method="post" action="check.php">  
<!--fieldset-->  
<label><strong>Morning Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="1" onclick="chkcontrol(0)">&nbsp;7:00 am to 8:00 am<br>  
   <input type="checkbox" name="ckb[]" value="2" onclick="chkcontrol(1)">&nbsp;8:00 am to 9:00 am<br>  
   <input type="checkbox" nam

Open in new window

OK. You'll want the datepicker within the <form> otherwise that info will never be sent to the server. The rest of it looks OK, so try without the JS and see what you get.
This came back
array(1) { ["ckb"]=> array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" } }
Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19

Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19

Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19

Open in new window

That looks good - you're now getting the array of checkboxes. Post up the foreach loop in full - something's off with that
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_POST);
require_once('includes/common.php');
require_once('includes/secure.php');
require_once('includes/practice.php');

$therapistId = 123;
$date = '2020-05-27';
$available = true;

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeID) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date,
        $available,
    ]);
}
?>

Open in new window

array(2) { ["mysched"]=> string(28) "Wednesday, September 9, 2020" ["ckb"]=> array(4) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" } }
Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19

Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19

Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19

Notice: Undefined variable: timeId in /home/audiodigz/public_html/THERAPIST/check.php on line 19 

Is it the timeID ? fileld  in the table its time_id
OK. PHP is case-sensitive and you're setting a variable called $timeID in the foreach() and then trying to access it with $timeId within the loop - they're different (notice the capital D !! )

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date,
        $available,
    ]);
}

Open in new window

Better...but not inserting into the table.
array(2) { ["mysched"]=> string(28) "Wednesday, September 9, 2020" ["ckb"]=> array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" } }

Open in new window

OK,

Make sure your error reporting is turned on!

Unless you're manipulating the date, then you'll get an error - like I said, you need to insert the date in a specific format. Easiest way to do this is to create a new DateTime from the POSTed data and then use format() to set it to the correct value for the DB. Something like this:

$therapistId = 123;
$available = 1;
$date = new DateTime($_POST['mysched']);

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date->format('Y-m-d'),
        $available,
    ]);
}

Open in new window

error reporting is on.  Mercy...
array(2) { ["mysched"]=> string(28) "Wednesday, September 9, 2020" ["ckb"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } }
Fatal error: Uncaught Error: Call to a member function format() on string in /home/audiodigz/public_html/THERAPIST/check.php:20 Stack trace: #0 {main} thrown in /home/audiodigz/public_html/THERAPIST/check.php on line 20 
Hmmm. If you're getting an error calling format() on a string, then it sounds like you've maybe missed the new DateTime part:

$date = new DateTime($_POST['mysched']);

Again, as a sanity check, dump the value of $date after you've called the above line:

var_dump($date);
Notice: Undefined variable: date in /home/audiodigz/public_html/THERAPIST/check.php on line 5
NULL
Errr - that seems odd seeing as though you'd just set it !!

Post up the code as you have it and I'll take a look
check.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($date);
require_once('includes/common.php');
require_once('includes/secure.php');
require_once('includes/practice.php');

$therapistId = 123;
$available = 1;
$date = new DateTime($_POST['mysched']);

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date->format('Y-m-d'),
        $available,
    ]);
}
?>

Open in new window


The main page..
<div id="datepicker"></div>
   <form name=checktimes method="post" action="check.php">  
   <input id="SD" type="text" name="mysched" value="Session Date" readonly/>
   <div id="times">
   

<!--form name=checktimes method="post" action="check.php"-->  
<!--fieldset-->  
<label><strong>Morning Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="1" onclick="chkcontrol(0)">&nbsp;7:00 am to 8:00 am<br>  
   <input type="checkbox" name="ckb[]" value="2" onclick="chkcontrol(1)">&nbsp;8:00 am to 9:00 am<br>  
   <input type="checkbox" name="ckb[]" value="3" onclick="chkcontrol(2)">&nbsp;9:00 am to 10:00 am<br>
   <input type="checkbox" name="ckb[]" value="4" onclick="chkcontrol(3)">&nbsp;10:00 am to 11:00 am<br>
   <input type="checkbox" name="ckb[]" value="5" onclick="chkcontrol(4)">&nbsp;11:00 am to 12:00 pm<br>
<br><label><strong>Afternoon Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="6" onclick="chkcontrol(5)">&nbsp;12:00 pm to 1:00 pm<br>
   <input type="checkbox" name="ckb[]" value="7" onclick="chkcontrol(6);">&nbsp;1:00 pm to 2:00 pm<br>  
   <input type="checkbox" name="ckb[]" value="8" onclick="chkcontrol(7)">&nbsp;2:00 pm to 3:00 pm<br>  
   <input type="checkbox" name="ckb[]" value="9" onclick="chkcontrol(8)">&nbsp;3:00 pm to 4:00 pm<br>
   <input type="checkbox" name="ckb[]" value="10" onclick="chkcontrol(9)">&nbsp;4:00 pm to 5:00 pm<br>
<br><label><strong>Evening Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="11" onclick="chkcontrol(10)">&nbsp;5:00 pm to 6:00 pm<br>
    <input type="checkbox" name="ckb[]" value="12" onclick="chkcontrol(11)">&nbsp;6:00 pm to 7:00 pm<br> 
   <input type="checkbox" name="ckb[]" value="13" onclick="chkcontrol(12)">&nbsp;7:00 pm to 8:00 pm<br>
    <input type="checkbox" name="ckb[]" value="14" onclick="chkcontrol(13)">&nbsp;8:00 pm to 9:00 pm<br> 
   <input type="checkbox" name="ckb[]" value="15" onclick="chkcontrol(14)">&nbsp;9:00 pm to 10:00 pm<br>
<br>
<span class="advice">Limit is 10 sessions per day.</span> 
<br
><br><input type="submit" class="btn3"value="Submit Changes">  
    <!--/fieldset-->  
</form>
  
<!--div id=msg></div><br><br>
<p class='prev'><a href=checkbox-limit.php>Session Limit</a></p>
</div-->

Open in new window

OK. In the code above, you've tried var_dumping the $data BEFORE you've actually set it. The var_dump needs to go AFTER you've set it:

$therapistId = 123;
$available = 1;
$date = new DateTime($_POST['mysched']);

var_dump($date);

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

Open in new window

Notice: Undefined variable: date in /home/audiodigz/public_html/THERAPIST/check.php on line 5
NULL
Notice: Undefined index: mysched in /home/audiodigz/public_html/THERAPIST/check.php on line 12
object(DateTime)#5 (3) { ["date"]=> string(26) "2020-09-09 17:13:27.135392" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
Warning: Invalid argument supplied for foreach() in /home/audiodigz/public_html/THERAPIST/check.php on line 16 
Right - something weird is going on with your code. Earlier, we definitely had the mysched index and we certainly had the ckb array from the POST data, but those errors above indicate that something has changed, because you're now not getting them.

Having said that, you're getting an error saying mysched doesn't exist, and yet you've managed to create a new DateTime object from it, so it must exists !!

Post up your code again so I can see exactly what's going on.
main page...
<div id="datepicker"></div>
   <form name=checktimes method="post" action="check.php">  
   <input id="SD" type="text" name="mysched" value="Session Date" readonly/>
   <div id="times">
   

<!--form name=checktimes method="post" action="check.php"-->  
<!--fieldset-->  
<label><strong>Morning Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="1" onclick="chkcontrol(0)">&nbsp;7:00 am to 8:00 am<br>  
   <input type="checkbox" name="ckb[]" value="2" onclick="chkcontrol(1)">&nbsp;8:00 am to 9:00 am<br>  
   <input type="checkbox" name="ckb[]" value="3" onclick="chkcontrol(2)">&nbsp;9:00 am to 10:00 am<br>
   <input type="checkbox" name="ckb[]" value="4" onclick="chkcontrol(3)">&nbsp;10:00 am to 11:00 am<br>
   <input type="checkbox" name="ckb[]" value="5" onclick="chkcontrol(4)">&nbsp;11:00 am to 12:00 pm<br>
<br><label><strong>Afternoon Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="6" onclick="chkcontrol(5)">&nbsp;12:00 pm to 1:00 pm<br>
   <input type="checkbox" name="ckb[]" value="7" onclick="chkcontrol(6);">&nbsp;1:00 pm to 2:00 pm<br>  
   <input type="checkbox" name="ckb[]" value="8" onclick="chkcontrol(7)">&nbsp;2:00 pm to 3:00 pm<br>  
   <input type="checkbox" name="ckb[]" value="9" onclick="chkcontrol(8)">&nbsp;3:00 pm to 4:00 pm<br>
   <input type="checkbox" name="ckb[]" value="10" onclick="chkcontrol(9)">&nbsp;4:00 pm to 5:00 pm<br>
<br><label><strong>Evening Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="11" onclick="chkcontrol(10)">&nbsp;5:00 pm to 6:00 pm<br>
    <input type="checkbox" name="ckb[]" value="12" onclick="chkcontrol(11)">&nbsp;6:00 pm to 7:00 pm<br> 
   <input type="checkbox" name="ckb[]" value="13" onclick="chkcontrol(12)">&nbsp;7:00 pm to 8:00 pm<br>
    <input type="checkbox" name="ckb[]" value="14" onclick="chkcontrol(13)">&nbsp;8:00 pm to 9:00 pm<br> 
   <input type="checkbox" name="ckb[]" value="15" onclick="chkcontrol(14)">&nbsp;9:00 pm to 10:00 pm<br>
<br>
<span class="advice">Limit is 10 sessions per day.</span> 
<br
><br><input type="submit" class="btn3"value="Submit Changes">  
    <!--/fieldset-->  
</form>
  

Open in new window

check.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($date);
require_once('includes/common.php');
require_once('includes/secure.php');
require_once('includes/practice.php');

$therapistId = 123;
$available = 1;
$date = new DateTime($_POST['mysched']);
var_dump($date);
$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date->format('Y-m-d'),
        $available,
    ]);
}
?>

Open in new window

Hmmm. Not sure what's going on. Your check.php script is not receiving the POST data, which is causing the errors you're seeing. Is there something else going on that you're not showing (Javascript for example). You had this problem earlier when you dumped the POST array, but I thought you'd fixed that.

Go back to adding in the following at the start of your script and see what you get:

var_dump($_POST);
This is what came back...
Notice: Undefined variable: date in /home/audiodigz/public_html/THERAPIST/check.php on line 5
NULL array(1) { ["ckb"]=> string(1) "4" }
Notice: Undefined index: mysched in /home/audiodigz/public_html/THERAPIST/check.php on line 12

Warning: Invalid argument supplied for foreach() in /home/audiodigz/public_html/THERAPIST/check.php on line 16

Open in new window

Yep - your script isn't receiving your POST data - it seems to be receiving something else instead (a single string called ckb)

You had this exact problem further back in the conversation and you said you fixed it by disabling/removing the Javascript. It now appears that you've added that JS back in, re-introducing the problem. Remove the Javascript and it should fix the problem. There's obviously something going on with your JS that prevent the normal data from submitting.
Hi Chris, Javascript is still REM'd out  I'm attaching the page so you have the complete picture...edit-schedules.php  also chaged the date field to session_date.  That error is not coming up anymore.  Is date a reserved word?  Also just caught this....
<form name=checktimes method="post" action="check.php">  
   <input id="SD" type="text" name="mysched" value="Session Date" readonly/>

Open in new window

<form name="checktimes" method="post" action="check.php">  
   <input id="SD" type="text" name="mysched" value="Session Date" readonly/>

Open in new window

form name was not in quotes..the input id SD is the date field....
Hmmm. I don't know. Your code looks fine, but based on that code, your errors are impossible !! There's something I'm not seeing. In your code you have several elements within the <form>, including an array of ckb[] checkboxes and a mysched text input, but for some reason, when your check.php script receives the POST request, it only sees a single ckb text box.

You'll need to do some sanity checking on your own - make sure you are actually submitting to the correct php script. When you load up your HTML page, view the source to make sure it's showing the correct code (i.e. you're not loading up the wrong HTML file or that it's not cached etc.)
Chris, could this be the problem?
<input id="SD" type="text" name="mysched" value="Session Date" readonly/>

Open in new window

the value? "Session Date"  also I added the session_date to the check.php file instead of date.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once('includes/common.php');
require_once('includes/secure.php');
require_once('includes/practice.php');
$therapistId = 123;
$available = 1;
$session_date = new DateTime($_POST['mysched']);
$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $sessionDate->format('Y-m-d'),
        $available,
    ]);
}
?>

Open in new window

When I do this no errors come up, nut no insert either..
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//var_dump($date);
//require_once('includes/common.php');
require_once('includes/secure.php');
//require_once('includes/practice.php');
var_dump($_POST);
$therapistId = 123;
$available = 1;
$session_date = new DateTime($_POST['mysched']);
//var_dump($session_date);
$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $session_date->format('Y-m-d'),
        $available,
    ]);
}
?>

Open in new window

It wouldn't explain why your POST data is wrong.

This input:

<input id="SD" type="text" name="mysched" value="Session Date" readonly>

Should get sent to the check.php as this:

$_POST['mysched']

This line:

$session_date = new DateTime($_POST['mysched']);

Should create a new variable called $session_date which you'd need to use in your execute() statement. You're using $sessionDate which doesn't exist so that will throw an error.

You've also changed the column name in your query, so make sure you've changed the column name in your database.

All of this is completely irrelevant if you can't figure out why your form is not being posted to the php script. Get that part fixed first and we can move on (you've already fixed this at some point, so you've done something since then to break it again)
OK,

So does your dump of POST data now show the correct info

Does the dump of $session_date show the correct data

Have you changed the column name in your mysql database (to session_date)
Yes I changed the field in the table and in the query...
Now getting this back..
Notice: Undefined index: mysched in /home/audiodigz/public_html/THERAPIST/check.php on line 12

Notice: Undefined variable: db in /home/audiodigz/public_html/THERAPIST/check.php on line 14

Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/audiodigz/public_html/THERAPIST/check.php:14 Stack trace: #0 {main} thrown in /home/audiodigz/public_html/THERAPIST/check.php on line 14 
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once('includes/common.php');
require_once('includes/secure.php');
require_once('includes/practice.php');

$therapistId = 123;
$available = 1;
$sessionDate = new DateTime($_POST['mysched']);

$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $sessionDate->format('Y-m-d'),
        $available,
    ]);
}
?>

Open in new window

This is getting stranger.

The mysched index error is because you're still not getting the POST data - you haven't confirmed what var_dump($_POST) showed you. You can't move forward on this in any way until you figure out why your're not getting the form data!

The Undefined db error is new !! That's saying that you haven't declared your $db variable - i.e. your database connection, or if you have, you've changed it to be something other that $db. That's been working all along, so you must have changed something.
Strange indeed.  I'm going to strip this down to plain vanilla and start over...I'll keep you posted on it..
Hey David,

I was about to suggest the same thing. Start very simple and work from there. Create a new script and call it debug.php with just the following (nothing else):

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

echo "*** DEBUG ***" . PHP_EOL;
var_dump($_POST);

Open in new window

Now change the action on your form to point to debug.php and run your HTML page , tick some checkboxes and click on the submit button.

Report back with the FULL output.
I moved it all to one page for testing...
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//var_dump($date);
require_once('includes/common.php');
require_once('includes/secure.php');
require_once('includes/practice.php');
//var_dump($_POST);
$therapistId = 123;
$available = 1;
$sessionDate = new DateTime($_POST['mysched']);
//var_dump($session_date);
$stmt = $db->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $sessionDate->format('Y-m-d'),
        $available,
    ]);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<div id="datepicker"></div>
   <form action="" method="post" >  
   <input id="SD" type="text" name="mysched"/>
   <div id="times">
   

<!--form name=checktimes method="post" action="check.php"-->  
<!--fieldset-->  
<label><strong>Morning Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="1" onclick="chkcontrol(0)">&nbsp;7:00 am to 8:00 am<br>  
   <input type="checkbox" name="ckb[]" value="2" onclick="chkcontrol(1)">&nbsp;8:00 am to 9:00 am<br>  
   <input type="checkbox" name="ckb[]" value="3" onclick="chkcontrol(2)">&nbsp;9:00 am to 10:00 am<br>
   <input type="checkbox" name="ckb[]" value="4" onclick="chkcontrol(3)">&nbsp;10:00 am to 11:00 am<br>
   <input type="checkbox" name="ckb[]" value="5" onclick="chkcontrol(4)">&nbsp;11:00 am to 12:00 pm<br>
<br><label><strong>Afternoon Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="6" onclick="chkcontrol(5)">&nbsp;12:00 pm to 1:00 pm<br>
   <input type="checkbox" name="ckb[]" value="7" onclick="chkcontrol(6);">&nbsp;1:00 pm to 2:00 pm<br>  
   <input type="checkbox" name="ckb[]" value="8" onclick="chkcontrol(7)">&nbsp;2:00 pm to 3:00 pm<br>  
   <input type="checkbox" name="ckb[]" value="9" onclick="chkcontrol(8)">&nbsp;3:00 pm to 4:00 pm<br>
   <input type="checkbox" name="ckb[]" value="10" onclick="chkcontrol(9)">&nbsp;4:00 pm to 5:00 pm<br>
<br><label><strong>Evening Sessions</strong></label><br>
   <input type="checkbox" name="ckb[]" value="11" onclick="chkcontrol(10)">&nbsp;5:00 pm to 6:00 pm<br>
    <input type="checkbox" name="ckb[]" value="12" onclick="chkcontrol(11)">&nbsp;6:00 pm to 7:00 pm<br> 
   <input type="checkbox" name="ckb[]" value="13" onclick="chkcontrol(12)">&nbsp;7:00 pm to 8:00 pm<br>
    <input type="checkbox" name="ckb[]" value="14" onclick="chkcontrol(13)">&nbsp;8:00 pm to 9:00 pm<br> 
   <input type="checkbox" name="ckb[]" value="15" onclick="chkcontrol(14)">&nbsp;9:00 pm to 10:00 pm<br>
<br>
<span class="advice">Limit is 10 sessions per day.</span> 
<br
><br><input type="submit" class="btn3"value="Submit Changes">  
    <!--/fieldset-->  
</form>
</body>
</html>


Open in new window

Just saw your post... doing now.

This is weird.  I changed the form to debug.php but it keeps saying check.php  I have cleared the cache severeal times and restarted the browser...still.
Notice: Undefined index: mysched in /home/audiodigz/public_html/THERAPIST/check.php on line 12

Notice: Undefined variable: db in /home/audiodigz/public_html/THERAPIST/check.php on line 14

Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/audiodigz/public_html/THERAPIST/check.php:14 Stack trace: #0 {main} thrown in /home/audiodigz/public_html/THERAPIST/check.php on line 14

Open in new window

Sounds like you're viewing the wrong page !!
OK its working now.  I checked the server.  It wasn't updating then it did!

*** DEBUG *** array(2) { ["mysched"]=> string(28) "Thursday, September 10, 2020" ["ckb"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } }
Perhaps we should move it to the top of the page and do ajax like we did before?  Would that be simpler?
Let's stick with the standard POST for now - adding in AJAX is something to do once you've got the script working.

That DEBUG dump you've just shown is perfect. That's exactly what we should have been receiving, so now let's build on it. First off, add in your include to grab your database connection. I don't know which file that is so you may need to edit the code below.

We'll also build a new DateTime from the POSTed data. Your script should now look like this:

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

require_once 'includes/common.php';

echo "*** DEBUG ***" . PHP_EOL;

$date = new DateTime( $_POST['mysched'] );

var_dump($_POST, $db, $date);

Open in new window

Run it again and see what you get. At this point, we're just confirming that we have POST data, we can create a DateTime from it, and that you have Database connection stored in the $db variable.

If that all works, we can hen move on to the Database code.
Here you go.  That pesky db error again.
*** DEBUG ***
Notice: Undefined variable: db in /home/audiodigz/public_html/THERAPIST/debug.php on line 18
array(2) { ["mysched"]=> string(28) "Thursday, September 10, 2020" ["ckb"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } } NULL object(DateTime)#3 (3) { ["date"]=> string(26) "2020-09-10 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

Open in new window

OK. So check in your included file what you've called the database connection. It's been working all along with $db so something's changed.
I'm seeing $con  we used $con on the other queries as well...
Ahh OK. Right, so we need to use $con.

Now we can move on to the DB stuff, so you new script will look like this:

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

require_once 'includes/common.php';

echo "*** DEBUG ***" . PHP_EOL;

$date = new DateTime( $_POST['mysched'] );
$therapistId = 123;
$available = 1;

$stmt = $con->prepare("INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (?, ?, ?, ?)");

foreach ($_POST['ckb'] as $timeId) {
    $stmt->execute([
        $therapistId,
        $timeId,
        $date->format('Y-m-d'),
        $available,
    ]);
}

Open in new window

Run that and assuming no erorrs, check your Database to see if the records have been inserted correctly.
*** DEBUG ***
Notice: Undefined variable: db in /home/audiodigz/public_html/THERAPIST/debug.php on line 18
array(2) { ["mysched"]=> string(28) "Thursday, September 10, 2020" ["ckb"]=> array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" } } NULL object(DateTime)#3 (3) { ["date"]=> string(26) "2020-09-10 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

No updates in the table.
What !!! Line 18 simply says $timeId - there's absolutely no reference to $db in the code I posted. We only refer to the connection once and that's on line 13 - it's called $con.

I've no idea what's going on any more

I'm guessing you've still got some of the old code in place that tries to var_dump stuff out (including the $db variable maybe ??). It's important that you use the code I post EXACTLY as I post it - if you start doing your own thing, then I lose track of where we're at.

If you're getting no updates in the table, post up your common.php file (strip out your password) so I can check the $con settings.
This is common..
session_start();
require_once("includes/config.php");
require_once("includes/database.php");

/** 
 * Send JSON response back to therapist
 */
function sendJSON($resp, $terminate = true) {
    header('Content-type: application/json');
    echo json_encode($resp);
    if ($terminate) die();
}
/**
 * Check if email is available
 */
function checkEmailAvailable($con, $table, $email) {
   $result = false;
   if ($email) {
      $query = "SELECT `therapist_email` FROM `{$table}` WHERE `therapist_email`=?";

      if ($stmt = mysqli_prepare($con, $query)) {
         mysqli_stmt_bind_param($stmt, "s", $email);
         mysqli_stmt_execute($stmt);
         mysqli_stmt_store_result($stmt);
         $result = mysqli_stmt_num_rows($stmt) == 0;
         mysqli_stmt_close($stmt);
      }
   }
   return $result;
}

/**
 * Check referrer against supplied domain
 * SERVER_DOMAIN defined in client-config.php
 */
function checkReferrer($domain = SERVER_DOMAIN) {
   $domainUrl = strtolower($domain);
   $referrer = isset($_SERVER['HTTP_REFERER']) ? strtolower($_SERVER['HTTP_REFERER']) : false;
   $referrerUrl = parse_url($referrer);
    return strpos($referrerUrl['host'], $domainUrl) !== false;
}


Open in new window

This is config..
$tablename     = "tbl_therapist";
$logtablename  = "tbl_therapist_log";
$silo_prefix   = 'therapist';
$silo_folder   = '';

//define('SERVER_DOMAIN', 'http://localhost:6500');
define('SERVER_DOMAIN', 'audiodigz.com');

define('SESSION_ID', '__SESSION_USER_ID');
define('HOME_PAGE', '/index.php');
define('REGISTER_REDIRCT', 'login.html');
define('SILO_FOLDER', '/THERAPIST/');
//define('SILO_FOLDER', '');
/**
 * Database settings
 */

define('DB_SERVER','localhost');
define('DB_USER','');
define('DB_PASS' ,'');
define('DB_NAME', 'HMS2020A');


/**
 * To prevent sub pages from being called directly
 */
define('HOST_PAGE', true);

Open in new window

This is database
require_once('includes/config.php');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$userid = isset($_SESSION[SESSION_ID]) ? $_SESSION[SESSION_ID] : false;

if ($userid) {
    $query = <<< QUERY
SELECT `{$silo_prefix}_name` FROM `{$tablename}` WHERE `{$silo_prefix}_id` = ?
QUERY;

    $stmt = mysqli_prepare($con, $query);
echo mysqli_error($con);    
    mysqli_stmt_bind_param($stmt, "d", $userid);

    $result = mysqli_execute($stmt);
    mysqli_stmt_bind_result($stmt, $username);
    mysqli_stmt_fetch($stmt);
    mysqli_stmt_close($stmt);
}


Open in new window

Hang on ! That Database config is using MySQLi - you said right at the start that you were using PDO !! Are you NOT using PDO ??
Yes I do have PDO as well..

Open in new window

$dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_SERVER;
$db = new PDO($dsn, DB_USER, DB_PASS);
I have both connections as I am in the process of switching over...
PDO_connection.php
$dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_SERVER;
$db = new PDO($dsn, DB_USER, DB_PASS);
??? And now we're back to a connection called $db !!

If you have a PDO connection called $db, I'm assuming you're creating that in some file somewhere, and if so, then why are you not including that file instead of the mysqli ($con) one.
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
Warning: Use of undefined constant DB_NAME - assumed 'DB_NAME' (this will throw an Error in a future version of PHP) in /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php on line 12

Warning: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' (this will throw an Error in a future version of PHP) in /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php on line 12

Warning: Use of undefined constant DB_USER - assumed 'DB_USER' (this will throw an Error in a future version of PHP) in /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php on line 13

Warning: Use of undefined constant DB_PASS - assumed 'DB_PASS' (this will throw an Error in a future version of PHP) in /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php on line 13

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2005] Unknown MySQL server host 'DB_SERVER' (0) in /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php:13 Stack trace: #0 /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php(13): PDO->__construct('mysql:dbname=DB...', 'DB_USER', 'DB_PASS') #1 /home/audiodigz/public_html/THERAPIST/debug.php(5): require_once('/home/audiodigz...') #2 {main} thrown in /home/audiodigz/public_html/THERAPIST/includes/pdo_connection.php on line 13 
Right - you need to start doing some logical thinking here !

Use of undefined constant DB_NAME

Have you actually included the config that defines these (I'm gonna guess NOT!). If you're including the PDO connection file, then make sure you've including the config file that contains those constant definitions at the start of it.
Now I did.  sorry getting loopy!  It returned this..
*** DEBUG ***

Just *** DEBUG ***   nothing else
WooHoo ! No errors is a good thing. Now check your Database :)
No ERRORS!!! No updates on the table.

Are you kidding me !!

Right - let's add in a little more debugging and see how we go. In the code below, I've grabbing the ID each time a new records is inserted and dumping that. I'm also grabbing the result of the execute() call. Run your code with this and report back what you get:

foreach ($_POST['ckb'] as $timeId) {
    $success = $stmt->execute([
        $therapistId,
        $timeId,
        $date->format('Y-m-d'),
        $available,
    ]);
    $id = $db->lastInsertId();
    var_dump($success, $id);
}

Open in new window

*** DEBUG *** bool(false) string(1) "0" bool(false) string(1) "0" bool(false) string(1) "0"
OK,

So - your query failed to run which points to something being wrong with this:

INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (?, ?, ?, ?)

We need to turn on Exceptions for your PDO connection. Post up your PDO connection file and I'll tell you where to do that. In the meantime, double check the table schema at the database level to make sure it's correct. Also, while you're there, manually run a query (using something like PHPMyAdmin or similar):

INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (123, '2', '2020-09-10', 1);

Run it exactly like above and see what happens
The Query works.
[SQL] INSERT INTO tbl_set_times (therapist_id, time_id, session_date, available) VALUES (123, '2', '2020-09-10', 1);
Affected rows: 1
Time: 0.079s

Open in new window

New record inserted.
The PDO file...
$dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_SERVER;
$db = new PDO($dsn, DB_USER, DB_PASS);

Open in new window

OK, good.

To turn on Exceptions for PDO, your file needs to look like this:

$dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_SERVER;
$db = new PDO($dsn, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Open in new window

Once you've done that, re-run your html page and see what the debug.php script shows. It should now display any errors coming from PDO and hopefully explain why the query didn't work
*** DEBUG *** bool(false) string(1) "0" bool(false) string(1) "0" bool(false) string(1) "0" bool(false) string(1) "0"
User generated image
Odd.

Right - more debugging :) Let's dump some error info:

foreach ($_POST['ckb'] as $timeId) {
    $success = $stmt->execute([
        $therapistId,
        $timeId,
        $date->format('Y-m-d'),
        $available,
    ]);
    $id = $db->lastInsertId();
    var_dump($stmt->errorInfo(), $success, $id);
}

Open in new window

Here you go...
*** DEBUG *** array(3) { [0]=> string(5) "22001" [1]=> int(1406) [2]=> string(45) "Data too long for column 'available' at row 1" } bool(false) string(1) "0" array(3) { [0]=> string(5) "22001" [1]=> int(1406) [2]=> string(45) "Data too long for column 'available' at row 1" } bool(false) string(1) "0" array(3) { [0]=> string(5) "22001" [1]=> int(1406) [2]=> string(45) "Data too long for column 'available' at row 1" } bool(false) string(1) "0" array(3) { [0]=> string(5) "22001" [1]=> int(1406) [2]=> string(45) "Data too long for column 'available' at row 1" } bool(false) string(1) "0" array(3) { [0]=> string(5) "22001" [1]=> int(1406) [2]=> string(45) "Data too long for column 'available' at row 1" } bool(false) string(1) "0" array(3) { [0]=> string(5) "22001" [1]=> int(1406) [2]=> string(45) "Data too long for column 'available' at row 1" } bool(false) string(1) "0"

Open in new window

Ahh right !! OK, what I would suggest you do here is to change the datatype for the available column from bit to boolean. This would then take a true/false value and keep things simple. Once you've done that to the table, change the value you're assigning to $available and re-run your code:

$date = new DateTime( $_POST['mysched'] );
$therapistId = 123;
$available = true;

...

Open in new window

YESSS!
*** DEBUG *** array(3) { [0]=> string(5) "00000" [1]=> NULL [2]=> NULL } bool(true) string(3) "108" array(3) { [0]=> string(5) "00000" [1]=> NULL [2]=> NULL } bool(true) string(3) "109" array(3) { [0]=> string(5) "00000" [1]=> NULL [2]=> NULL } bool(true) string(3) "110"

Open in new window

User generated image
Get In !!!

Nice one David. Finally we have progress.

You can now remove your var_dump debugging info and you should be good to go. If you decide you want to AJAXify your form later on, this script is a great starting point.

I think the key take-away from all of this is DEBUG, DEBUG, DEBUG !! It is without doubt the most valuable skill you can ever have as a developer - the better you can debug, the better you can write code.
Thank you so much!  It was a tough one but you did it!  I'm taking a break then I will tackle it again with the variables and the Ajax... Once again you are appreciated!  And thank you!
You're welcome David :)
Thank you