Jump to content

For Loop To Assign A Variable


Amster

Recommended Posts

Hello,

 

I want to use a loop to assign a new variable to a different value from my database. So for example, $item[1] = 'item1' from my database, $item[2] = 'item2' from my database and so forth until 'item100'. I have tried using the following code:

 

$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
while ($row_settings = mysql_fetch_array($rs_settings)) {
for( $i = 1; $i < 100; $i++ )
{
$item[$i] = $row_settings['item . $i'];
}
}

 

And the following code for output:

 



for( $i = 1; $i < 100; $i++ ){
echo $item[$i];
}
?>


 

But it just echoes nothing. Could someone help me with my code so I can get this working?

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/269742-for-loop-to-assign-a-variable/
Share on other sites

I've only made `item1`, `item2` in the database so far but I intend on making the rest. Shouldn't it still be outputting the values of `item1`, `item2` or does it requires me to put every field first in the database?

 

Edit: I tried changing it from <100 to <2 and it still echoes nothing.

I've only made `item1`, `item2` in the database so far but I intend on making the rest.

 

 

That is 100% the wrong way to do it. You should be setting those values as different rows in either that or another table. Eg:

create table users (
 userid int
 name varchar(100)
);

create table user_items (
 userid int,
 itemvalue varchar(100)
);

 

You'd store the main user details in the users table, then for every item you want to add you create a new row in the user_items table with the user's id and item data.

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.