1

I want to save data into an array and use session after inputting data. I have tried and succeeded. but I want to display some data taken from the database and save it to an array and session earlier. I have tried adding database queries, but the data can only hold one data only.

<?php
if (!isset($_SESSION)) {
session_start();
# code...
}


include_once "AlgoCBC.php";

function additem($jns, $hrg, $hrg_tw, $total, $kt_satu, $kt_dua, $kt_tiga, $kt_empat, $kt_lima, $kt_enam, $kt_tujuh){
    

    if (empty($_SESSION['$jns'])) {

        include "koneksi.php";

        $_SESSION['jenis'] = array();
        $jen = array_push($_SESSION['jenis'], $jns);
    
        
        foreach ($jen as $id) {
            
        
        $sql = mysqli_query($kns, "Select stok.id_stok as id_stok, merk.nama_merk as nama_merk, model.nama_model as nama_model, stok.warna as warna FROM stok INNER JOIN model On stok.id_model=model.id_model INNER JOIN merk ON model.id_merk=merk.id_merk where id_stok = '$id' ") or die(mysqli_error($kns));



                 while ($y=mysqli_fetch_array($sql)) {
                    $mrk[] = implode("", DekripCBC($y['nama_merk']));
                    $mdl[] = implode("", DekripCBC($y['nama_model']));
                    $wrn[] = implode("", DekripCBC($y['warna']));
                 }

                }

    $_SESSION['merk'] = array();
    $_SESSION['model'] = array();
    $_SESSION['warna'] = array();
    $_SESSION['kuantiti'] = array();
    $_SESSION['harga'] = array();
    $_SESSION['harga_tawar'] = array();
    $_SESSION['harga_jual'] = array();
    }

    $kn = $kt_satu + $kt_dua + $kt_tiga + $kt_empat + $kt_lima + $kt_enam + $kt_tujuh;


    array_push($_SESSION['merk'], $mrk);
    array_push($_SESSION['model'], $mdl);
    array_push($_SESSION['warna'], $wrn);
    array_push($_SESSION['kuantiti'], $kn); 
    array_push($_SESSION['harga'], $hrg);
    array_push($_SESSION['harga_tawar'], $hrg_tw);
    array_push($_SESSION['harga_jual'],$total);


}


 function display(){

if (!empty($_SESSION['merk'])) {
    $merk = $_SESSION['merk'];
$model =    $_SESSION['model'];
$warna =    $_SESSION['warna'];
$kuantiti =     $_SESSION['kuantiti'];
$harga =    $_SESSION['harga'];
$harga_tawar = $_SESSION['harga_tawar'];
$harga_jual = $_SESSION['harga_jual'];


$tgl = date('d-m-y');

echo '  <table class="table table-bordered table-striped text-gray-900" id="dataTable""> 
        <thead>

                <tr>
                <th colspan="5">'.$tgl.'</th>
                </tr>
                    <tr>

                      <th>Jenis Sepatu </th>
                      <th>Kuantiti</th>
                      <th>Harga</th>
                      <th>Harga Tawar</th>
                      <th>Total</th>
                    </tr>
              </thead>
              
    ';
$total=0;
$no = 1;
    for ($i = 0; $i < count($model); $i++ ) { 
        //$mk = implode("", $merk[$i]);
        //$md = implode("", $model[$i]);
        //$wr = implode("", $warna[$i]);
        
        echo '<tbody>
                    
                        <tr>
                        
                        <td>'.$merk[$i].' '.$model[$i].' '. $warna[$i].'</td>
                        <td>'.$kuantiti[$i].'</td>
                        <td>'.$harga[$i].'</td>
                        <td>'.$harga_tawar[$i].'</td>
                        <td>'.number_format($harga_jual[$i],0,',','.').'</td></tr>';

        $total = $total + $harga_jual[$i];
        

    }

    echo '<tr><td>Total</td>
            <td></td>
            <td></td>
            <td></td>
            
            
            <td>'.number_format($total,0,',','.').'</td>
            
            </tr> </tbody> </table>';

    }else {

    }
  }



  ?>

enter image description here

enter image description here

so it can only hold 1 data only. if new data is input, the previous data is lost.

Egash
  • 13
  • 4
  • 1
    The problem is that you are _overwriting_ all three of your variables inside the while loop in each iteration, so _of course_ only the values from the last record “survive”. You need to push the values into arrays inside that loop already. – CBroe Jul 07 '20 at 09:18
  • I'm a little confused, can you edit my code, which part should I change – Egash Jul 07 '20 at 09:25
  • 1
    How to add items to those session entries, is something you already know - you are already doing it in the code you have shown. So move that part, into the while loop. – CBroe Jul 07 '20 at 09:31
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Jul 09 '20 at 21:30

2 Answers2

0

you are overwriting all three of your variables inside the while loop in each iteration, That's why you are just getting one result(which was the last data set that was executed inside the while loop.

There are basically 3 things that you can do to solve your issue.

1.Use an array to store all the results that you get from the loop

    while ($y=mysqli_fetch_array($sql)) {
          $mrk[] = implode("", DekripCBC($y['nama_merk']));
          $mdl[] = implode("", DekripCBC($y['nama_model']));
          $wrn[] = implode("", DekripCBC($y['warna']));
     }

2.Use an pre-defined array to store all the results that you get from the loop using array_push.

  /**There are 3 ways to define an empty array. You can use any of the following
      1.$emptyArray = [];
      2.$emptyArray = array();
      3.$emptyArray = (array) null;
   * */

  $dataSet =[];

    while ($y=mysqli_fetch_array($sql)) {
          $data['mrk'] = implode("", DekripCBC($y['nama_merk']));
          $data['mdl'] = implode("", DekripCBC($y['nama_model']));
          $data['wrn'] = implode("", DekripCBC($y['warna']));

        array_push($dataSet ,$data);
     }

3.concatenate the values into your variable

  while ($y=mysqli_fetch_array($sql)) {
    // I have added a seprator(,) for all the variables so that there will be a , after every result and it wouldn't make you confused at the end
         $mrk .= implode("", DekripCBC($y['nama_merk'])).','; 
         $mdl .= implode("", DekripCBC($y['nama_model'])).',';
         $wrn .= implode("", DekripCBC($y['warna'])).',';
  }

I would highly recommend you to use method no.1 or no.2.

I hope this would help you to solve your issue.

If you want to search for multiple ids using the query:(since i mentioned in the comments i'll add it to here.)

EX:

//You have multiple ids that you get from the session.

$jns = [12,13,4,5]; 

 //So now you can use a foreach loop to loop all the ids and use the query to get relevant data

 foreach($jns as $id){
     $sql = mysqli_query($kns, "Select stok.id_stok as id_stok, merk.nama_merk as nama_merk, model.nama_model as nama_model, stok.warna as warna FROM stok INNER JOIN model On stok.id_model=model.id_model INNER JOIN merk ON model.id_merk=merk.id_merk where id_stok = '$id' ") or die(mysqli_error($kns));

    while ($y=mysqli_fetch_array($sql)) {
       $mrk[] = implode("", DekripCBC($y['nama_merk']));
       $mdl[] = implode("", DekripCBC($y['nama_model']));
       $wrn[] = implode("", DekripCBC($y['warna']));
     }
  }

By this method you can get all the data for the ids that is mentioned above and assign it to the array.

Hirumina
  • 738
  • 1
  • 9
  • 23
  • I try to use number 2, but the data in the database does not appear and only holds the last data. I tried number 3, the data in the database appears but only holds the last data. I tried number 1 with the following error: Notice: Array to astring conversion on line 91 : '.$merk[$i].' '.$model[$i].' '.$warna[$i].' – Egash Jul 08 '20 at 06:31
  • can you give all the code which parts should be changed ?, maybe not in the while loop, but there is a section below that must be changed – Egash Jul 08 '20 at 06:34
  • 1
    problem number 1 in the conver string array has been resolved by imploade. but it still can only capture the latest data – Egash Jul 08 '20 at 07:03
  • ARe you sure that your query returns more than 1 data set? – Hirumina Jul 08 '20 at 07:07
  • Yes, I tried the first data input, but after the second data input, the first data was lost and only the second data appeared. – Egash Jul 08 '20 at 07:14
  • is there something that might have been missed in another part of the script? – Egash Jul 08 '20 at 07:15
  • @Egash it should return 1 data set only.Because you have filtered the data set using `where id_stok = '$jns' ` in your query.So it will return the data set which has the value of $jns for `id_stock` column. – Hirumina Jul 08 '20 at 07:23
  • yes it is made like that, so I want to retrieve data from the database namely: nama_merk, nama_model and warna on id_stok. I want to save in an array and session. but when it is displayed, the data in the array displayed is not a query – Egash Jul 08 '20 at 07:45
  • Where id_stok = '$jns' in quey, delete ? – Egash Jul 08 '20 at 07:47
  • So you want get multiple results from your query.You will get only one data set since you are filtering the data set using the primary key and you can't find any duplicate primary keys.(you can find only one `id_stock` which has the value `1`) – Hirumina Jul 08 '20 at 07:59
  • yeah right, so i want to get some data based on id_stok. I saved that data into an array_push. when the data will appear all the data in the array that appears. – Egash Jul 08 '20 at 08:14
  • yes!! all the data that has the id that you are searching for will appear – Hirumina Jul 08 '20 at 08:17
  • And if you want to search for multiple ids, you can use a `forach` loop and use the query inside the loop.And you can store all the data using one of the method that i have mentioned in the answer – Hirumina Jul 08 '20 at 08:18
  • I do not understand, sorry I'm still a beginner. can you give an example – Egash Jul 08 '20 at 08:22
  • Sure.I'll add an example to my answer. – Hirumina Jul 08 '20 at 08:24
  • @Egash I've updated the answer.I hope it will give you some idea – Hirumina Jul 08 '20 at 08:30
  • hi ... I tried changing it, but it's still the same, and the data doesn't appear. can you please check my code update above. is there something wrong – Egash Jul 09 '20 at 11:12
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Jul 09 '20 at 21:29
0

The thing which is causing this issue is because it is adding to variable and same variable gets overrite everytime because of same variable name. You eitheir need to empty those variables push them to some other place and can use it.

For this we can use php function array_push where we will push them into master array.

$master = array();
while ($y=mysqli_fetch_array($sql)) {
                    $data['mrk'] = implode("", DekripCBC($y['nama_merk']));
                    $data['mdl'] = implode("", DekripCBC($y['nama_model']));
                    $data['wrn'] = implode("", DekripCBC($y['warna']));
                    array_push($master,$data);
                 }
Jaymin
  • 1,643
  • 1
  • 18
  • 39
  • I try to use, but the data in the database does not appear and only holds the last data. – Egash Jul 08 '20 at 06:32
  • can you give all the code which parts should be changed ?, maybe not in the while loop, but there is a section below that must be changed – Egash Jul 08 '20 at 06:35