Choice from a DB in the casual order on PHP
There are some problems for which it is necessary to give out in the casual order on page some recordings, read - out of a database. For example, it can be banner krutilka or section of a site " a casual idea ". And so, it is possible to realize this problem in several ways, and I would like to tell about two of them in this lesson.
Such obraom I have made the first script which printed a casual aphorism on page:
.... // database connection code
$query = " select * from quotes ";
$result = mysql_query ($query);
$randval = rand (0, mysql_num_rows ($result) - 1);
$quotetext = mysql_result ($result, $randval, 1);
$quoteauthor = mysql_result ($result, $randval, 2);
print " $quotetext <br> $quoteauthor ";
What does{makes} this code? First we form sql search which pulls out all recordings from the table quotes. Then we generate a random number which does not exceed quantity{amount} of the recordings received from a database. With the help of function mysql_result () we receive casual recording, that is we use casual value, as number{room} of lines in a returned set. The third argument of this function is number{room} of a column, that is a field of recording in which that it is necessary to give out is stored{kept}.
So, lacks of this code are obvious:
1.) Before using the generator of random numbers, it is necessary for us somewhere above in the program preliminary to initialize this generator. By the way it is done{made} with function srand ().
2.) It is necessary to store{keep} all time in mind{wit} number{room} of a column in which the necessary information is stored{kept}. And if suddenly the quantity{amount} of columns in the table will change, we should change such code.
Now let's consider other code which does{makes} too most, but in more convenient way.
$query = " select * from quotes order by rand () limit 1 ";
$result = mysql_query ($query);
$row = mysql_fetch_array ($result);
print ($row ['text'] '. <br> '. $row ['author']);
In this example casual values are generated with the server of a database and returns each time different lines. It is a little having changed a code, it is possible to deduce{remove} the table in the casual order:
$query = " select * from quotes order by rand () ";
$result = mysql_query ($query);
while ($row = mysql_fetch_array ($result)) {
print ($row ['text'] '. <br> '. $row ['author'] '. <hr> ');
}
Unless this variant is not better?
I think, that it is better!

|