2

I have two arrays and below is the output. The first array is my all the list and the second I am getting by the user selected.

$specification=getgeneralSpecifications($pdo); // getting below array

Array(
    [0] => Array
        (
            [sp_id] => 1
            [specifications_name] => example 1
        )

    [1] => Array
        (
            [sp_id] => 2
            [specifications_name] => example 2
        )

    [2] => Array
        (
            [sp_id] => 3
            [specifications_name] => example 3
        )

    [3] => Array
        (
            [sp_id] => 4
            [specifications_name] => example 4
        )

    [4] => Array
        (
            [sp_id] => 5
            [specifications_name] => example 5
        )

    [5] => Array
        (
            [sp_id] => 6
            [specifications_name] => example 6
        )

)
    $getgeneral = explode(",",$info['developerprofile']['general_Specifications']); // getting below output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

I have to display all the lists from the database and I have checked the check box depending on the second array value getting the form database.

I tried the below code and I am getting the output but missing one value. I mean if I have array 1,2,3,4 then I am getting on 1,2,3

    <?php 
    $specification=getgeneralSpecifications($pdo);
    $getgeneral = explode(",",$info['developerprofile']['general_Specifications']);

    foreach ($specification as $key=> $row) {
      $checked="";
      if(in_array($key, $getgeneral)){
        $checked="checked";
          }
      ?>
      <li><label><?php echo $row['specifications_name'];?></label>
        <div class="form-check">
          <input class="form-check-input custom-checkbox generalsinglecheck" type="checkbox" value="<?php echo $row['sp_id'];?>" name="general_specification[]" <?php echo $checked;?>>
        </div>
      </li>
    <?php } ?>
user9437856
  • 2,360
  • 2
  • 33
  • 92
  • `in_array()` is your friend here. See [the manual](https://www.php.net/manual/en/function.in-array.php). – Michel Jun 13 '21 at 08:45
  • @Michel, then do I need to use foreach? – user9437856 Jun 13 '21 at 08:53
  • Just `if ( in_array ( $row['sp_id'], $your_user_array ) )` – Michel Jun 13 '21 at 09:09
  • @Michel, I updated the code in the question. Can you check it once? – user9437856 Jun 13 '21 at 09:29
  • You still have to use `$checked` somewhere. Now it is set and never used. And, before the `if ( in_array...` put `$checked="";` to reset the value with every loop. – Michel Jun 13 '21 at 09:35
  • Yes, I added after the checkbox name..but now i am not getting list as well as output. – user9437856 Jun 13 '21 at 09:41
  • 2
    @mickmackusa, Actually I have to show all the list with selected .getgeneralSpecifications() displaying all the list and $getgeneral displaying the slected. – user9437856 Jun 13 '21 at 14:19
  • 1
    @mickmackusa, Yes, you are right, before I tried the same but now some scenarios changed to now I have to show all the lists on the edit page where the user can update more listss. – user9437856 Jun 13 '21 at 14:21
  • @mickmackusa, wait let me update... I was an experiment with so many codes to solve my issue – user9437856 Jun 13 '21 at 14:29
  • @mickmackusa, I just updated the question and explanation also. I am getting one number missing while using in_array() – user9437856 Jun 13 '21 at 14:33
  • @mickmackusa, $specification displaying first array list and $getgeneral displaying the second array list – user9437856 Jun 13 '21 at 14:43

2 Answers2

2

This is a simple matter of mistaking the row indexes and the sp_id values (which are also numeric).

Your $key variable would be more aptly named $index, but the truth is that you don't need to declare that variable at all. Instead, reference the row's sp_id when comparing against the $getgeneral array and everything will be fine.


I recommend creating a clean template string to use as you iterate. printf() is great for this technique. This way you can neatly tab your markup and you don't need to use messy interpolation/concatenation mixed with inline condition blocks.

Oh, and I'll demonstrate array destructuring within the foreach(), but you don't necessarily need to do this -- you can just access the subarray values by their key if you wish.

Code: (Demo) (Demo without destructuring)

function getgeneralSpecifications() {
    return [
        ['sp_id' => 1, 'specifications_name' => 'example 1'],
        ['sp_id' => 2, 'specifications_name' => 'example 2'],
        ['sp_id' => 3, 'specifications_name' => 'example 3'],
        ['sp_id' => 4, 'specifications_name' => 'example 4'],
        ['sp_id' => 5, 'specifications_name' => 'example 5'],
        ['sp_id' => 6, 'specifications_name' => 'example 6'],
    ];
}

$checked = explode(',', '1,2,4');

echo "<ul>";
foreach (getgeneralSpecifications() as ['sp_id' => $id, 'specifications_name' => $name]) {
    printf(
        '<li>
            <label>%s</label>
            <div class="form-check">
                <input class="form-check-input custom-checkbox generalsinglecheck"
                       type="checkbox"
                       value="%d"
                       name="general_specification[]"
                       %s>
            </div>
        </li>',
        $name,
        $id,
        in_array($id, $checked) ? 'checked' : ''
    );
}
echo "</ul>";

Output:

<ul>
    <li>
        <label>example 1</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="1"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 2</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="2"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 3</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="3"
                   name="general_specification[]"
                   >
        </div>
    </li>
    <li>
        <label>example 4</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="4"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 5</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="5"
                   name="general_specification[]"
                   >
        </div>
    </li>
    <li>
        <label>example 6</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="6"
                   name="general_specification[]"
                   >
        </div>
    </li>
</ul>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

i dont understant your code ,But why you not try use your checkbox as an array in java script, By try something like,

Example :

<?php
//you-php-response.php
require "database.php";
$db = new DataBase();
if (isset($_POST['sp_id']) ) {
    if ($db->dbConnect()) {
        if ($db->setlist("my_list_2", $_POST['sp_id'])) {
            echo "Add to list";

        } else echo "something went wrong";
    } else echo "Error: Database connection";
} else echo "All fields are required";

and your database.php :

<?php
require "DataBaseConfig.php";

class DataBase
{
    public $connect;
    private $stm;
    protected $servername;
    protected $username;
    protected $password;
    protected $databasename;

    public function __construct()
    {
        $this->connect = null;
        $this->stm = null;
        $dbc = new DataBaseConfig();
        $this->servername = $dbc->servername;
        $this->username = $dbc->username;
        $this->password = $dbc->password;
        $this->databasename = $dbc->databasename;
    }

    function dbConnect()
    {
        $this->connect = new PDO('mysql:host='.$this->servername.';dbname='.$this->databasename.'', $this->username, $this->password);
        return $this->connect;
    }

    function setlist($table, $sp_id)
    {
         $this->stmq = "INSERT INTO ".$table."( `sp_id_token`) VALUES ('?')";
         $this->stm = $this->connect->prepare($this->stmq) ;
          if ($this->stm->bind_param("ssis", $this->my_sup_id)) {
              $this->my_sup_id = "$sp_id";
              $this->stm->execute();
             return true;
           } else return false;  
    }

    function getmycheckboxRander()
    {
         $this->stmq = "SELECT* FROM `my_list_1` ";
         $this->stm = $this->connect->prepare($this->stmq);
         $this->stm->execute();
         $this->result =   $this->stm->fetchAll();
         $this->body = array();
         foreach($this->result as $this->row){
              $this->sp_id= $this->row['sp_id'];
              $this->my_sup_name = $this->row['sup_name'];
              $this->body[] = array("<div class='card ew-card card-body'><p><input 
             type='checkbox' name='type' value=".$this->sp_id." />".$this->my_sup_name." </p></div>");
        }
     return $this->body;
    }
}

and 'DataBaseConfig.php'

<?php

class DataBaseConfig
{
    public $servername;
    public $username;
    public $password;
    public $databasename;

    public function __construct()
    {

        $this->servername = 'localhost';
        $this->username = 'root';
        $this->password = 'pass@';
        $this->databasename = 'data_base';

    }
}

?>

and your script should be like

<?php
require_once "database.php";
$db = new DataBase();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
<?php if($db->dbConnect()){?>
    var mylist= <?= json_encode($db->getmycheckboxRander())?>;
<?php }?>
    document.getElementById("mylistarray").innerHTML = mylist;
        $('button').on('click', function() {
            var array = [];
            $("input:checkbox[name=type]:checked").each(function() {
                var sup_id = $(this).val();
                jQuery.ajax({
                   url:'your-php-response.php',
                    type:'post',
                    data:'sp_id ='+sup_id ,
                        success:function(result){
                          window.location.href=window.location.href 
                     }
                 });
            });          
        });
</script>
//then the result
<div id="mylistarray"></div>
  <button class="btn btn-success" >Add to list</button>
Adan
  • 58
  • 2
  • 10
  • That mysqli query is insecure/unstable and should not be used by anyone. `mysqli_connect_error()` should never be presented to the end user. Procedural mysqli syntax is more verbose / less attractive versus object-oriented syntax. – mickmackusa Jun 13 '21 at 14:12
  • @Adan, I tried one more solution and it's almost working but I am getting one missing. I updated the code in the question. – user9437856 Jun 13 '21 at 14:16
  • 1
    Please understand that when you post an answer on Stack Overflow, you are NEVER only speaking to the OP -- you are speaking to thousands of future researchers. Never recommend code that you know is insecure or that you wouldn't write in your own professional application. Your answers must demonstrate the very best of your knowledge every time. – mickmackusa Jun 13 '21 at 14:22
  • 2
    I don't think you are rude. I do not recommend `mysqli_real_escape_string()` -- it is no longer the modern standard. Only prepared statements should be used. Besides that, there is evidence that the OP using PDO not MySQLi. – mickmackusa Jun 13 '21 at 16:40
  • I am not the best. I am just a junior developer who is trying to learn php well. – mickmackusa Jun 13 '21 at 16:56
  • @mickmackusa I hope it's work fine now as I proms , thanx for your time . – Adan Jun 13 '21 at 18:33