Jump to content

PHP SQL - Insert Imploded Array into Table


oliverj777

Recommended Posts

Hello,

 

I'm working on a form that once submitted, it inserts the result into my SQL table, but I'm trying to get it so it will update an imploded array.

 

EG: current SQL table is "red,blue,green". Then user submits 'white', the SQL table should then update to: "red,blue,green,white" (notice how its added to the end). This is what I have so far:

 

$attack_out = $info['attack_out'];
$attack_out_split = explode(",", $attack_out);

if(isset($_POST["submit_attack"])){
   $attack_user = $_GET["attack"]; 		// user - sent from form
   //$troops_send = $_POST["troop_send"];	// ammount - sent from form

   $attack_user_array = array();
   $i = 0;
   $max = (count($attack_out_split) + 1);
   while($i < $max){
      $reverse = ($max - 1) - $i;
      $attack_user_array[$i] = $attack_out_split[$reverse];
      $attack_user_array[$max - 1] = $attack_user;
      $i++;	
   }
   $attack_user_glue = implode(",",$attack_user_array);
   $result = mysql_query("UPDATE users SET attack_out='$attack_user_glue' WHERE username='$username'");
}

 

 

I can't figure out the algorithm in my while loop. Would appreciate any help, thanks

As Jesirose rightly pointed out, you dont need to fetch the existing field data in variable, explode it, attached new string at end and implode it again.

since it is comma separated, you can just append it at the end.

 

If you want to insert the text in middle of the field and sequence does matter then you will have to do what you are trying to do.

 

$result = mysql_query("UPDATE users SET attack_out=CONCAT(attack_out, '".$attack_user."') WHERE username='$username'");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.