1

I would like a new item to be added to an array if a button is pressed

This is my code...

$engineers = array();

if(isset($_POST['add_user'])){
    $engineers[] = $_POST['engineer'];
    $array_count = count($engineers);
}

All it does is replace the only item in the array rather than add to it, where am I going wrong?

Thanks

The form used is

$dropdown = '<select id="engineer" name="engineer" class="select_engineer" type="text" name="engineer" /><option>Select Diary</option>';
while($row = mysql_fetch_assoc($result)){
    $dropdown .= "\r\n<option value='{$row['user_name']}'>{$row['user_name']}</option>";
}
$dropdown .= "\r\n</select>";

">

(The list of engineers is populated from a MySQL database).

There isn't anywhere else that adds to the array, I just want a button that will add the engineers user name to the array

2
  • 6
    It's only ever going to run once, and add the contents of $_POST['engineer'] to the array - where else are you adding things to $engineers? Commented Sep 5, 2012 at 18:02
  • Please also insert the code for your form. Commented Sep 5, 2012 at 18:03

3 Answers 3

1

If you're having Client / Server communication each time a button is pressed, you're gonna have to use Session.

Whenever you have a client/server request, a new thread is created in your Web Server, which has no idea what happened in other threads. If the client clicked a button and sent an information to the server that was added to a variable and then got his answer, all that was in PHP memory was deleted already. If you want to go to the server, go back to the client, back to the server and so on, you're gonna have to store the information somewhere, somehow. It might be useful to use a Session to store everything and at the end of it do something, like e-commerces.

Sign up to request clarification or add additional context in comments.

Comments

0

your array resets every time you reload the page. you have to store the data in cookies or sessions or database or ... simple idea :

<?php
session_start();
if(!isset($_SESSION['engineers']))
$engineers = array();
else
$engineers = unserialize($_SESSION['engineers']);
if(isset($_POST['add_user'])){
    $engineers[] = $_POST['engineer'];
    $array_count = count($engineers);
}
$_SESSION['engineers'] = serialize($engineers);

1 Comment

That makes complete sense, never thought about the page refreshing on the form submit. Thanks for your help
0

Everytime your submit the form the whole code is re-executed. Which means $engineers is set to an empty array everytime. The submitted data is added to this empty array, which means it will be the only data available.

Use $_SESSION for persistence.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.