note 68588 deleted from function.mysql-fetch-row by bjori

From: Date: Thu, 07 Sep 2006 22:38:31 +0000
Subject: note 68588 deleted from function.mysql-fetch-row by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-116878@lists.php.net to get a copy of this message
Note Submitter: Victor Ocampo - Vicale Corp Reason: wtf ---- thor_victor on hotmail dot com Hi every one, i guess that as me theres lots of ppl who need to use <b><strong>mysql_fetch_row()</b></strong> as it really should work, i mean, SELECT A DEFINED ROW from a query result! well i dont know why online does not appear the Pierre-Yves Lapointe Brisson comment, but hes right, he says that mysql doesn't manage sql data as dataset, only as simple variables, SO.... In the case you want to select specific rows from a query result heres your solution (contributions for smaller and more efficient code are acepted): first, do all the required stuff: connect data base and always do error handlers, then do your query (example): $sql = "SELECT * FROM table "; $result = mysql_query ($sql); then catch the rows count, its important considering that you have to know how many registers there are for choosing them: $count = mysql_num_rows($result); ok now simply parse your result into a Array variable, this will make it so easy to access to any record at any level you want: while ($row = mysql_fetch_row($result)) { $records[] = $row; } Then you are ready to select any info you want: print_r ($records[4]) = This will show entire 4 row of your original query. echo $records[4][2] = This will show the 2 column of 4 row, this is cheap i know, but.. Now the real stuff, lets say we did all this crap to randomly choose X registers from Y results in query, theres 2 important things, be able to chose any row you want,this is solved up, AND make the random choose dont reapeat, unless it doesnt matter for you. Heres my solution: for ($i=0; $i<5; $i++) //Here im picking only 5 random registers to show { $picked = rand(0,$count-1); //picking a row $verify[$i] = $picked; //registering the selected rows into a var while (count(array_count_values($verify)) < $i+1) //making all registers unique, so we wont get repeated values { $picked = rand(0,$count-1); $verify[$i] = $picked; } print_r ($records[$picked]); echo "<br>"; //simply printing the results! } Enjoy, i know after reading this its so easy, but it took a little when i tried to c if there was a function to be able to choose a defined row from a result, which actually there is "mysql_result", but i dont know the reason, this function ONLY select the fisrt column in the desired row! This is frustrating and sensless.

« previous php.notes (#116878) next »