Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5

Thread: loops

  1. #1
    Regular Coder
    Join Date
    Jul 2005
    Location
    Oxfordshire, UK
    Posts
    144
    Thanks
    0
    Thanked 0 Times in 0 Posts

    loops

    Hi,
    i want to use a while loop to add info from the db into variables named item1, item2 etc.

    i have the below query which i know wont work because it doesnt like the variable names $item$i... how can i get it to automatically create and name the variables for each $i?


    PHP Code:
    $query1 "SELECT * from quotes where quote_id = $quote_id";
    $result1 = @mysql_query ($query1); //run the query
    while ($row1 mysql_fetch_array
    ($result1MYSQL_ASSOC)) {
    $i 0;
    $item$i $row1['item$i'];
    $i $i 1;


  • #2
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,027
    Thanks
    2
    Thanked 315 Times in 307 Posts
    Make your life easier and use an array for $item. Using sequentially named variables will require you to keep track of how many of them there are. With an array, you can use count() to find out how many or you can simply use a foreach() loop it iterate over all elements of the array.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #3
    Regular Coder
    Join Date
    Jul 2005
    Location
    Oxfordshire, UK
    Posts
    144
    Thanks
    0
    Thanked 0 Times in 0 Posts
    i already know taht there are only 20...

  • #4
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    You need to use an array or assign the values for each one. here is the array answere

    PHP Code:
    <?PHP
    $query1 
    "SELECT * from quotes where quote_id = $quote_id";
    $item=array();
    $result1 = @mysql_query ($query1); //run the query
    while ($row1 mysql_fetch_array
    ($result1MYSQL_ASSOC)) {
    $item[sizeof($item)]= $row1;
    }
    ?>
    This will infact return a multidimensional array
    You can not say you know how to do something, until you can teach it to someone else.

  • #5
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,642
    Thanks
    2
    Thanked 405 Times in 397 Posts
    No it won't. Why would you use sizeof() anyway, instead of simply appending the value to the array and letting PHP assign the key?
    PHP Code:
    $arr = array();
    $arr[] = $row1


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •