Correct way to use list()?

Discussion in 'PHP' started by Tony Brar, Jun 27, 2012.

  1. #1
    is this the correct way to use list()?

    $sql = "SELECT * FROM users WHERE user_id='$_SESSION[userid]'";$query = mysql_query($sql, $con);$userinfo = mysql_fetch_array($query);list( , , , , ,$coins, $uploads, $consecdays) = $userinfo;
    PHP:
    Thanks
     
    Solved! View solution.
    Tony Brar, Jun 27, 2012 IP
  2. #2
    You would use list() to assign multiple scalar variables to a list of items in an array. So list($color, $car, $state) = array("red", "corvette", "new york"); would assign the array values accordingly. If you wanted to skip assigning corvette to $car you would omit that variable and just have a comma.

    I would advise you to use PDO to interact with mySQL. It's prettier, safer, and will make your life easier.

    Example:

    
    
    $dbname = "mydatabase";
    $dbuser = "userblah";
    $dbpass = "pass123";
    
    $dbh = new PDO('mysql:host=localhost;dbname=$dbname', $dbuser, $dbpass);
    
    $someval = "blah";
    
    $sql = "SELECT col1 FROM SomeTable WHERE somCol = :someval;";
    $sth = $dbh->prepare($sql);
    $sth->bindParam(":someval", $someval);
    $sth->execute();
    
    $sth->bindColumn('col1', $col1);
    
    $sth->fetch();
    
    print "col1's value is: " . $col1;
    
    
    PHP:
     
    NetStar, Jun 27, 2012 IP
  3. akhileshbc

    akhileshbc Active Member

    Messages:
    98
    Likes Received:
    1
    Best Answers:
    5
    Trophy Points:
    75
    #3
    Yes.

    Tested it using the following code:
    
    $userinfo = array('blah1', 'blah2', 'blah3', 'blah4', 'blah5', 'blah6', 'blah7', 'blah8');
    list( , , , , ,$coins, $uploads, $consecdays) = $userinfo;
    
    echo $coins . '<br />' . $uploads . '<br />' . $consecdays;
    
    PHP:
    Edit: NetStar has already posted in lightning speed :)
     
    akhileshbc, Jun 27, 2012 IP
  4. gapz101

    gapz101 Well-Known Member

    Messages:
    524
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    150
    #4
    @topic, yes it is correct. But the code is not good. You might need to use other approach as NetStar posted.
     
    gapz101, Jun 29, 2012 IP
  5. Tony Brar

    Tony Brar Active Member

    Messages:
    220
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    75
    #5
    Thank you, Netstar, that's what I wanted to know!
    Also, thanks for adding that bit about PDO. I will definitely look into it.

    - Tony
     
    Tony Brar, Jun 30, 2012 IP