Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

How to receive random id from DataBase?

random mysql id receive

Best Answer Blimp, 11 December 2014 - 01:08 AM

Hey!

 

This would probably be best achieved by a random order by. In your query, add this to the end of your query:

 

ORDER BY RAND()

LIMIT 1

 

The rand is a method that returns a random row, the LIMIT is the amount of rows that you want to get back. In this case, you want a single row.  The end query would be something along the lines of:

 

SELECT * FROM klients WHERE status=free ORDER BY RAND() LIMIT 1

Go to the full post


This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1 AdrianWiercioch

AdrianWiercioch

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 10 December 2014 - 04:26 PM

Hi!

 

First I apologize for my english. I`m from Poland and I use this language only for creating php code :)

So, I have one problem in my script. I have to receive one random rekord from db with one condition. My code look like this:

$db = new PDO('mysql:host=localhost;dbname=callcentre', 'root');
$sql = 'SELECT * FROM klients WHERE status=free';
$results = $db->query($sql);

It`s simple. Code connects with db, select all columns from table which fulfil.

But next... I was traying fetch it by "$results->fetch()" and use array_rand() function, but it returns me only "id" or 0.

Please for solution for this.

 

* klients it is a simple table contains 4 columns: id|name|lastname|status

* what I want to recive? - One id where status is free.

 

Thanks for intresting and solutions!

 



#2 Blimp

Blimp

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 199 posts

Posted 11 December 2014 - 01:08 AM   Best Answer

Hey!

 

This would probably be best achieved by a random order by. In your query, add this to the end of your query:

 

ORDER BY RAND()

LIMIT 1

 

The rand is a method that returns a random row, the LIMIT is the amount of rows that you want to get back. In this case, you want a single row.  The end query would be something along the lines of:

 

SELECT * FROM klients WHERE status=free ORDER BY RAND() LIMIT 1



#3 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts

Posted 12 December 2014 - 03:27 PM

Welcome aboard Adrian,

 

Props to Blimp who gave you the right answer!



#4 AdrianWiercioch

AdrianWiercioch

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 13 December 2014 - 11:28 PM

Thank you BLIMP for solution!






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download