Skip to content

Instantly share code, notes, and snippets.

@netojoaobatista
netojoaobatista / 1lr-query.php
Last active December 15, 2015 18:39
Obtendo registros aleatórios de uma base sem utilizar ORDER BY RAND()
<?php
$pdo = new PDO('mysql:host=127.0.0.1;dbname=base', 'user', 'pswd');
$stm = $pdo->query('
SET @count = (SELECT COUNT(*) FROM tabela);
SET @query = CONCAT("SELECT * FROM `tabela` LIMIT 4 OFFSET ", 1 + FLOOR(RAND() * @count));
PREPARE stmt FROM @query;
EXECUTE stmt;
');