How to fetch full row associated with a column which is selected in dropdown list?

Tags: , ,



I have made a dropdown list which fetches data (name) from database and displays in options of dropdown list. Now I am trying to fetch full row of that selected name from the list and want to save each data into a variable for further usage. Can anyone guide me… This is my first project in PHP/MySQL, please help me…

Here is my code for dropdown list:

<form action="sel2.php" method="post">
  Player:
  <select name="data[]" multiple>
    <option disabled selected>-- Select Player --</option>
    <?php
        
        $records = mysqli_query($con, "SELECT * From bat");  // Use select query here 

        while($data = mysqli_fetch_array($records))
        {
            echo "<option value='". $data['name'] ."'>" .$data['name'] ."</option>";  // displaying data in option menu
        }   
        

    
  echo "</select>";

    


echo "<input type='submit' name='submit' value='Submit' />";
echo "</form>";
?>

I have managed to fetch the name and store it into a variable:

<?php 

      if(isset($_POST['submit'])){
        if(!empty($_POST['data'])) {
          foreach($_POST['data'] as $selected){
            $curdata = $selected;           
          }
            
          
        } else {
          echo 'Please select the value.';
        }

      }

?>

Which I have managed to get echo in another page (sel.php):

<!DOCTYPE html>
<html>
<head>
  <title>PHP Retrieve Data</title>
  
  <?php include "connection.php"; 
        include "sel2.php";// Using database connection file here ?>
</head>
<body>
<center>
<?php

echo $curdata, "<br>" , $batq;
?>


</center>
</body>

</html>

But how can I store all values of that particular row, for example:

$id = //id of selected name from dropdown list
$age = //age of selected name from dropdown list

etc etc

Answer

$_POST['data'] is an array of names, since you filled it with $data['name'] on your previous script.

There is no more data to store than the names… for that, you could for instance, serialize the record:

        while($data = mysqli_fetch_array($records))
        {
            echo "<option value='". serialize($data) ."'>" .$data['name'] ."</option>";  // displaying data in option menu
        }   

Now you’ll be getting an array of serialized records on the $POST['data'] parameter:

First, unserialize: $curdata = unserialize($selected);

Then access whatever field you need echo $curdata['age'];

Oh, and bear in mind this, if you assign $curdata to $selected inside a foreach… $curdata will always be the last $POST['data'] element, I don’t think you need the foreach in this case.



Source: stackoverflow