0

I have a table where all we have all of the packages. I want to select all of packages id. on page refresh I want to show a different package. I tried to do this with rand() but it doesn't if we don't have 1 id in package table. any suggestions?

function get_packages_id() {
  $pkg_count = count_all('ph_packages');
  $pkg_id = rand(1, $pkg_count);
  return $pkg_id;
}

$package = find_by_id($pkg_id, 'id', 'ph_packages');

<div class="card m-b-30">
    <div class="card-body text-center">
        <h4 class="mt-0 mb-3 header-title"><?php echo h($package['title']); ?> Only $<?php echo h($package['price']); ?></h4>
        <p><?php echo h($package['description']); ?></p>
        <?php if ($package['payment_method'] === 'default') { ?>
        <a href="pricing.php" class="btn btn-primary waves-effect waves-light"><?php echo h($package['button_text']); ?></a>
        <?php } else { ?>
        <a href="<?php echo $package['payment_method']; ?>" class="btn btn-primary waves-effect waves-light"><?php echo h($package['button_text']); ?></a>
        <?php } ?>
    </div>
</div>
  • When you say "but it doesn't if we don't have 1 id in package table", you mean if ids aren't consecutive (for example, 1 to 10, but 8 is missing)? – El_Vanja Mar 16 '20 at 07:23
  • @El_Vanja Yep, some of the ids are missing. because admin deleted that package. –  Mar 16 '20 at 07:25
  • 1
    You can randomize in SQL. Check out [this answer](https://stackoverflow.com/a/4329447/4205384). – El_Vanja Mar 16 '20 at 07:27
  • @El_Vanja okay, thank you so much :) –  Mar 16 '20 at 07:29

1 Answers1

0

to get random row then use RAND():

SELECT * FROM table_name
ORDER BY RAND()
LIMIT 1;
Antony Jack
  • 480
  • 2
  • 16