ph0bolus
ph0bolus

Reputation: 115

Query inserting 'Array' instead of value into database

Trying to set up a scheduler with a checkbox, when I check multiple time slots I would like the checked times to each be inserted into my table.

I have timeslots set up in my database as an enum, so this just displays all the times in checkbox form.

echo "<table>";
echo "<tr>";				
  echo("<td><input type=checkbox name=time_slot[] value='$option'>$option</td>");
echo "</tr>";
echo "</table>";

This code is supposed to insert each checked item into the database with all the same information bar the timeslot.

if(isset($_POST['submit']))
{
  $ts = $_POST['time_slot'];
  $db = new PDO ("mysql:host=localhost; dbname=zzzzz", "zzzzz", "12345");
  for ($i=0; $i<sizeof($ts);$i++)
  {
    $query = "INSERT INTO timeslot (date, duration, firstName, lastName) VALUES ('".$_POST['year']."-".$_POST['month']."-".$_POST['day']."', '$ts', '".$_SESSION['firstName']."', '".$_SESSION['lastName']."')";
	$state = $db->prepare($query);
	$state->execute();
	print_r($state);
  }
	print_r($ts);
Each loop for the print_r($state) outputs INSERT INTO timeslot (date, duration, firstName, lastName) VALUES ('2020-04-20', 'Array','John', 'Doe').

The print_r($ts) outputs all the timeslots that i've checked Array ( [0] => 4:20-4:40 PM [1] => 4:40-5:00 PM [2] => 5:00-5:20 PM )

How can I fix this problem? Thanks.

Upvotes: 0

Views: 131

Answers (2)

ranakrunal9
ranakrunal9

Reputation: 13558

Use time-slot as below to get comma separated value of it:

$ts = implode(",",$_POST['time_slot']);

Upvotes: 0

Ethan22
Ethan22

Reputation: 747

If you're looping through $ts, you might want to use the $i to grab the value at that index on each loop. '" . $ts[$i] . "'

$query = "INSERT INTO timeslot (date, duration, firstName, lastName) VALUES ('".$_POST['year']."-".$_POST['month']."-".$_POST['day']."', '" . $ts[$i] . "', '".$_SESSION['firstName']."', '".$_SESSION['lastName']."')";

Upvotes: 2

Related Questions