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
  1. #1
    New Coder
    Join Date
    Sep 2011
    Posts
    35
    Thanks
    18
    Thanked 1 Time in 1 Post

    Question PDO fetching objects - how to assign variables ?

    Hi guys,

    very simple I'm sure - what is the better way of assigning variables to rows in this case? I'm assuming this is probably a stupid way of doing it:

    PHP Code:
    $stmt $conn->prepare('SELECT id,make,model FROM products WHERE id > :id');
    $stmt->execute(array('id' => $id));
    $result $stmt->fetchAll();
    if ( 
    count($result) ) {
    foreach(
    $result as $row) {
    $id=$row[0];
    $make=$row[1];
    $model=$row[2];


  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Yep, you can use list.
    PHP Code:
    list($id$make$model) = $row

  • Users who have thanked Fou-Lu for this post:

    elem (01-10-2013)

  • #3
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,133
    Thanks
    12
    Thanked 332 Times in 328 Posts
    Tip: you don’t need ->fetchAll() for this, you can loop directly over $stmt
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • Users who have thanked Dormilich for this post:

    elem (01-10-2013)

  • #4
    New Coder
    Join Date
    Sep 2011
    Posts
    35
    Thanks
    18
    Thanked 1 Time in 1 Post
    Thanks guys, if there is any more ways I'll be glad to get to know them.

    Fou-Lu - I've used it and it works great. Cheers

  • #5
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,133
    Thanks
    12
    Thanked 332 Times in 328 Posts
    Quote Originally Posted by elem View Post
    if there is any more ways I'll be glad to get to know them.
    that depends upon what you want to do with the variables.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


  •  

    Posting Permissions

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