Jump to content

Recommended Posts

Hi,

I am trying to load numbers from a list in a MySQL database (I have no problem doing that) then I need to seperate them all out and have a variable for each.

For example, I have 6 comma seperated values stored in a datbase (1,2,3,4,5,6 for example) I then need to set a variable for each e.g. $n1 is set to 1, $n2 is set to 2, $n3 is set to 3, and so on (obviously these won't be the actual numbers, otherwise I could have just hard-coded them) and then I will be using these values in the rest of the script.

I can not change it so that the values from the database are provided any other way - they are always in this format.

Any help you can provide is much appreciated.
Ben
OK, so lets say the list in your database looks like this... 1,2,4,8,16,32

Would you want it like this:
$1 = 1
$2 = 2
$3 = 4
$4 = 8
$5 = 16
$6 = 32

Or this:

$1 = 1
$2 = 2
$4 = 4
$8 = 8
$16 = 16
$32 = 32

If I've read it right and it's the latter, then give this a try...

[code]<?php
// Select csv's from database
$sql = "SELECT column_name FROM table_name";
$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);

// Put each element into an array keyed on number
$values = explode(",", $row['column_name']);

// Make a variable out of each value
forach ($values as $k => $v){
  $$v = $v;
}
?>[/code]

All you need to do is replace my query with yours and change [code=php:0]$row['column_name'][/code] to the name of yor column.

Regards
Huggie

Regards
Huggie
PHP doesn't allow variable names that begin with numbers.

If you can use arrays instead of individual variables, just use the explode function. If you need individual variables, you can do something like:
[code]<?php
$sql = "SELECT column_name FROM table_name";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
list($a1,$a2,$a3,$a4,$a5,$a6) = explode(',',$row['column_name']);
?>[/code]

Ken
[quote author=kenrbnsn link=topic=121536.msg499878#msg499878 date=1168277783]
PHP doesn't allow variable names that begin with numbers.
[/quote]

Now I feel stupid, I was in coding mode, making sure everything was syntactically correct, I completely glossed over that fact.  :-X

Regards
Huggie
This thread is more than a year old. Please don't revive it unless you have something important to add.

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.

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