0

I need a little help with my PHP. Basically I have a field a page that I need the code to produce an outcome that looks like:

$existing_users=array('bra','vis','rfm'); 

Where it pulls the 'bra', 'vis', 'rfm' from the database.

So I figured cool lets make this into an array, and then explode it / separate it with '', Which I am not sure is the best approach, though I guess that's where my logic took me. And so I created the array

mysql_select_db($database_db, $db);
$result = mysql_query('SELECT * FROM clients') or exit(mysql_error());
while ($row = mysql_fetch_assoc($result)) {$array[] = $row['shortcode'];}

print_r($array);  

Which gives me this:

Array
(
    [0] => bra
    [1] => vis
    [2] => rfm
)

This is where I am stuck. I am not quite sure how to make things happen to my desired result. If anyone can provide me with advice I would be really appreciative.

7
  • what do you want to do with your result? Commented Aug 25, 2012 at 13:54
  • 1
    Whats the question? You access the array like echo $array[1]; which will output vis, also stop using mysql_* functions and move to PDO or mysqli Commented Aug 25, 2012 at 13:54
  • 1
    Did you ever print_r($existing_users); ? It will print out exactly what you create from MySQL Commented Aug 25, 2012 at 13:57
  • Sorry if I didn't structure my question very well. @mimiEAM the end result I want is: $existing_users=array('bra','vis','rfm'); Commented Aug 25, 2012 at 14:03
  • @MihaiIorga It wouldn't work as $existing_users is the end result that I want. I still need to push the data into the array from the database. Commented Aug 25, 2012 at 14:05

3 Answers 3

4

You can declare the array before the while loop and you can push the values into it like

$existing_users = array();
mysql_select_db($database_db, $db);
$result = mysql_query('SELECT * FROM clients') or exit(mysql_error());
while ($row = mysql_fetch_assoc($result)) {$existing_users[] = $row['shortcode'];}

print_r($existing_users);
Sign up to request clarification or add additional context in comments.

Comments

1

have you tried this ?

$existing_users=array($array[0],$array[1],$array[2]); 

a raw way of doing what you want , you could use a loop and push the element on the new array if the return of your query is too big

1 Comment

Thank you for your feedback. I thought of that, though that would also mean that there could only be three fields we would be looking at. The number of names I want to pull-in will be a variable depending on how many names are in the database.
1
foreach($array as $user){
    $existing_users[] = $user;
}

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.