PDO use Fetch to get the first row from a query (without using FetchAll first?) -


using php, pdo query games database, retrieve game available join. if use fetch bring last row meets criteria. want first row, i'm using fetchall looking @ first row retrieved. there way use fetch , tell first row. using fetchall seems gathering lot more data require.

i'm new of (animator trade), having got head around old mysql i've moved on using pdo seems great. building working asynchronous game server.

here's code, works wonder if more efficient, if did'nt use fetchall.

       //set variables use when searching random game in table        $player2_id = 0; //if 0 player 2 slot has not been filled.        $whose_turn = 2;  //if 2 player twos go...so join.           //is there random game join          $current_game = $db->prepare("select * games_database player2_id=? , whose_turn=?");         $current_game->execute(array($player_2_id, $whose_turn));          //fetch results         $random_game_to_use = $current_game->fetchall(pdo::fetch_assoc);          //get first of results         $firstavailablegame = $random_game_to_use[0];         $rand_game_name = $firstavailablegame['game_name']; 

i hope makes sense. or pearls of wisdom gratefully received. want stackoverflow has been incredibly helpful website in learning of coding php , pdo database queries. i've tried learn code 4 times in life starting stick nicely. first question... jon.

since have no order by clause in query, result set unsorted definition. might have sorting, not guaranteed.

since want "first" , not "last" row, want sort , therefore should specify desired sorting database sorts result set.

as have appended order something clause query, can further append asc or desc control direction of sorting , push liked row top (for example order desc). (this makes "last row first" or "first row last".)

then can (and should) limit result set 1 row, since want 1 row. append limit 1 query, retrieve row want.

you can use fetch() request first (and only) row, 1 want.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -