1

I'm new to PHP and I hope someone can help me. I have 4 PHP files and they are basically a form for the user to fill, then the system will navigate it to validate page, and user will click submit to save it. I have a problem in the checkbox part.

The error shows :

Notice: Array to string conversion in C:\xampp\htdocs\LM\LMvalidate_reservation.php

I have simplified the code to show only the checkbox part for easier understanding. I hope someone(s) can help me in this.

LMreservation.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="LMvalidate_reservation.php" method="post">
  
   <div class="col-md-4"><b>Please check (√ ) the module(s) that you want to attend:</b><br></div>
        <div class="col-md-8">
        <input type="checkbox" class="get_value" value="WEBOPAC Usage">WEBOPAC Usage<br>
  <input type="checkbox" class="get_value" value="Accessing Online Database Skill">Accessing Online Database Skill<br>
  <input type="checkbox" class="get_value" value="E-Books and E-Journals Accession">E-Books and E-Journals Accession<br>
  <input type="checkbox" class="get_value" value="Digital Collection Accession">Digital Collection Accession<br>
  <input type="checkbox" class="get_value" value="EQPS Exam Papers">EQPS Exam Papers<br>
  <input type="checkbox" class="get_value" value="Information Searching Strategy">Information Searching Strategy<br>
  <input type="checkbox" class="get_value" value="SCOPUS & Web Of Science Usage Skill">SCOPUS & Web Of Science Usage Skill<br>
  <input type="checkbox" class="get_value" value="Reference Management Software (EndNote & Mendeley)">Reference Management Software (EndNote & Mendeley)<br>
  <input type="checkbox" class="get_value" value="UiTM Institutional Repository (Thesis & Dissertation)">UiTM Institutional Repository (Thesis & Dissertation)<br>
  <input type="checkbox" class="get_value" value="Digital Map">Digital Map<br>
  <input type="checkbox" class="get_value" value="E-Newspaper (BLIS (Bernama Library & Infolink Service)">E-Newspaper (BLIS (Bernama Library & Infolink Service))<br>
  <input type="checkbox" class="get_value" value="Facility">Facility<br><br>
  </div>
   


          <script>
   $(document).ready(function(){
   $('#submit').click(function(){
   var insert = [];
   $('.get_value').each(function(){
   if($(this).is(":checked"))
   {
   insert.push($(this).val());
   }
   });
   insert = insert.toString();
   $.ajax({
   url: "insert.php",
   method: "POST",
   data:{insert:insert},
   success:function(data){
   $('#result').html(data);
   }
   });
   });
   });
     </script>
     

<input type="submit" name="LMreservation_form" value="Submit"> 


</form>

LMvalidate_reservation.php

<?php

if (isset($_POST['LMreservation_form'])) {

  $module = "";
  $count_error = 0;
  $msg = "";

  // validate if submitted variables empty show error msg else put in local variables

  }
  if (isset($_POST['module']) && ($_POST['module'] != ""))
    $module = $_POST['module'];
  else
  {
    $msg .= "Error: Please select your module.<br>";
    $count_error++;
  }

  if ($count_error > 0) {
    echo $msg;
    echo "$count_error error(s) detected.";
    die();
    // display error(s) here and stop
  }
}
else {
  echo "Error: You have execute a wrong PHP. Please contact the web administrator.";
  die();
}

?>

<!DOCTYPE html>
<html>
<head>

</head>

<body>

<form action="LMsave_reservation.php" method="post">
<table> 
     <tr>
      <td class="col-md-4 col-xs-4">Module:</td>
      <td class="col-md-8 col-xs-8"><?php print $module; ?><input type="hidden" name="module" value="<?php echo $module; ?>"></td>
    </tr>


  </table><br>

  <input type="submit" name="LMreservation_validate" value="Save My Reservation">


</form>

</body>
</html>

LMsave_reservation.php

<?php

if (isset($_POST['LMreservation_validate'])) {

  // Connection variables
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "lm_reservation";

  try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      // Prepare the SQL statement
      $stmt = $conn->prepare("INSERT INTO lmreservation(name, studentstaffid, faculty, contactno, email, program, participant, attandance, module, date, starttime, endtime) VALUES (:name, :studentstaffid, :faculty, :contactno, :email, :program, :participant, :attandance, :module, :date, :starttime, :endtime)");

      // Bind the parameters

      $stmt->bindParam(':module', $module, PDO::PARAM_STR);


      // insert a row

      $module = $_POST['module'];

      $stmt->execute();

      echo "Your application is successful. Have a nice day! :)";
      }

    catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

    $conn = null;
  }

 ?>

insert.php

<?php
if(isset($_POST["insert"]))
{
 $conn = mysqli_connect("localhost", "root", "", "lm_reservation");
 $query = "INSERT INTO lmreservation(modules) VALUES ('".$_POST["insert"]."')";
 $result = mysqli_query($conn, $query);
}
?>
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Siti
  • 31
  • 2
  • so the name of `checkbox` input is `module` ??., if so normally in PHP /HTML, all related check boxes should have same name and in when you take the checkbox value in PHP during ``POST`, it will bean Array. In your LMvalidate_reservation.php , you are attempting to print `$module` which has an array in this line ``, that is the reason you are getting Array to String conversion error. The solution is you should use `print_r` to see the array elements. – Reiah Paul Sam May 31 '17 at 05:10
  • yes, the name of checkbox input is module. So what should I do? – Siti May 31 '17 at 05:12
  • Why are you using `PDO` on `LMsave_reservation.php` and `mysqli_connect()` on the `insert.php` page? You should make one connection to simplify your code. What you have is not very maintainable. – Rasclatt May 31 '17 at 05:33
  • It works but only the first checked value are added.. – Siti May 31 '17 at 05:37
  • @Rasclat I know something was wrong about that but I'm not sure how to edit it. – Siti May 31 '17 at 05:41
  • Unfortunately you have a lot of issues in this set of scripts...I would start with setting up only one database connection method, I personally would stick with `PDO` and ditch the `mysqli_*` but that is personal preference. – Rasclatt May 31 '17 at 05:48
  • I would then compartmentalize your scripts more by creating some functions (classes/methods would be better). This will make your scripts more readable and easier to maintain. – Rasclatt May 31 '17 at 05:50

2 Answers2

3

First, in order to get an array for $module, the array syntax would need to be used (see this section of the PHP documentation for more information). For this, each checkbox input would need to have the name attribute added with value module[], like in the markup below:

<input type="checkbox" name="module[]" class="get_value" value="WEBOPAC Usage">WEBOPAC Usage<br>
<input type="checkbox" name="module[]" class="get_value" value="Accessing Online Database Skill">Accessing Online Database Skill<br>
<!-- repeated for all other checkboxes -->

Then when in LMvalidate_reservation.php, $module will be an array (refer to this answer for more information). In order to properly print out each element in the array (i.e. each value checked in the form), use a function like print_r() or iterate over the values with a construct like foreach.

<table> 
    <?php 
    foreach($module as $moduleItem) { 
        echo '<tr>
            <td class="col-md-4 col-xs-4">Module:</td>
            <td class="col-md-8 col-xs-8">'.$moduleItem.'<input type="hidden" name="module" value="'.$moduleItem.'"></td>
            </tr>';
    }?>   
</table>

See a demonstration of this in this phpfiddle. Note that because only one PHP file is allowed, the code from LMreservation.php and LMvalidate_reservation.php have been combined.

This is because the form (i.e. <form action="LMvalidate_reservation.php" method="post">) is being submitted the standard way (i.e. not asynchronously, like the jQuery AJAX code attempts to do).

Additionally, if you wanted that jQuery AJAX code to work, the submit button would need to have an id attribute set. So this line in reservation.php

<input type="submit" name="LMreservation_form" value="Submit"> 

Would need to be updated like this:

<input id="submit" type="submit" name="LMreservation_form" value="Submit"> 

That way the click handler (i.e. $('#submit').click(function(){...}) will be bound to clicks on an element that exists in the DOM.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
0

use a For loop instead in that file LMvalidate_reservation.php

<?php
 
if (isset($_POST['LMreservation_form'])) {
 
  $module = "";
  $count_error = 0;
  $msg = "";
 
  // validate if submitted variables empty show error msg else put in local variables
 
  }
  if (isset($_POST['module']) && ($_POST['module'] != ""))
    $module = $_POST['module'];
  else
  {
    $msg .= "Error: Please select your module.<br>";
    $count_error++;
  }
  
  if ($count_error > 0) {
 echo $msg;
    echo "$count_error error(s) detected.";
    die();
    // display error(s) here and stop
  }
}
else {
  echo "Error: You have execute a wrong PHP. Please contact the web administrator.";
  die();
}
 
?>

<!DOCTYPE html>
<html>
<head>
  
</head>

<body>

<form action="LMsave_reservation.php" method="post">
  
<table> 
  <?php foreach($module as $element) { ?>
  <tr>
      <td class="col-md-4 col-xs-4">Module:</td>
      <td class="col-md-8 col-xs-8"><?php print $element; ?><input type="hidden" name="module" value="<?php echo $element; ?>"></td>
    </tr>
  <?php } ?>
   
  </table><br>

  <input type="submit" name="LMreservation_validate" value="Save My Reservation">


</form>

</body>
</html>
Reiah Paul Sam
  • 555
  • 6
  • 16