Jump to content

PHP SQL - Insert Imploded Array into Table


oliverj777
 Share

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

Link to comment
Share on other sites

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'");

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • 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.