Search code examples
phpmysqlarraysinsertrelational

insert php array into mySql


I am looking for some guidance.

I have a data form field which I am inserting into a table and am looking to association the data with the id's of other relevant data. I was wondering if there was recommended way to insert an array of relevant Id's in relation to the information I am referring too.

Below is what Im thinking...

Eg. php reads

 <?php
 $name = $_POST['name'];
 $info = $_POST['information'];
 $id = $_POST['id'];
 $family = array();
 ?>
 <?php 

 $select = "SELECT * 
              FROM  `names_family` 
              WHERE  `name` LIKE  '$name'
              LIMIT 0 , 30";

 $selected  = mysql_query($select, $connection);
if(!$selected){
die("Hal 9000 says: Dave the select family name ID query failed " . mysql_error());}


 while($row = mysql_fetch_array($selected)){
       $familyId = $row[0];
       $familyName = $row[1];

 array_push($family, $familyName => $familyId);            

}

 $insertInfo = "INSERT INTO `family_info`.`info` 
            (`name`, `info`, `family`)
            VALUES (
            '$name', '$info', '$family');";

 $insertedInfo  = mysql_query($insertInfo, $connection);
if(!$insertedInfo){
die("Hal 9000 says: Dave the insert info query failed " .   mysql_error());}
 ?>

Is this a recommended way to relate information? Or is another way to achieve the same result?


Solution

  • there is another way

          $family=array()
         while($row = mysql_fetch_array($selected)){
               $familyId = $row[0];
               $familyName = $row[1];
    
          $family[]=$familyName.$familyId;            
    
        }
    
     $insertInfo = "INSERT INTO `family_info`.`info` 
                (`name`, `info`, `family`)
                VALUES (
                '$name', '$info', '$family');";