Print random field from a database

0

I have a small problem I have a functional code which generates a random word

$codigo = mysql_query("SELECT * FROM palabras WHERE categoria='b'");
mt_srand(time()); 
$max = mysql_num_rows($codigo);
$rand = mt_rand(1,$max); 
$obtener = mysql_query("SELECT * FROM palabras WHERE sub_categoria='$rand' AND categoria='b'");
while($ban = mysql_fetch_array($obtener)) { echo $ban['palabra']; }

but now I need to delete the field sub_categoria for other needs and try the following code

$codigo = mysql_query("SELECT * FROM palabras WHERE categoria='b'");
mt_srand(time()); 
$max = mysql_num_rows($codigo);
$rand = mt_rand(1, $max); 
$ban = mysql_fetch_array($codigo)
echo $ban['palabra'][$rand];

but it turns out that it does not work for me, it throws me some letters that are not in the database, if they help me it would be very helpful

    
asked by alvaro 28.09.2018 в 06:13
source

1 answer

0

The possible solution that you found would be on the following page: Method ROW_NUMBER ()

The page mentions the method ROW_NUMBER (), this method is used to extract the field or fields of a table according to its position, it would be applied in replacement of the following code (the first code of the question that has the sub_category).

$obtener = mysql_query("SELECT * FROM palabras WHERE sub_categoria='$rand' AND categoria='b'");

Considering that sub_category is a numeric field that you wish to eliminate, to obtain the query you must sort the words table and extract in the field with $ rand as position.

// Random = value of the table field words

    SELECT 
 ROW_NUMBER() OVER (
 ORDER BY Azar
 ) row_num,
Azar
FROM 
 palabras
ORDER BY 
Azar
where row_num=$rand
 ;
    
answered by 28.09.2018 в 09:42