Hi all,

I am working on a website that requires two queries from a table at the same time. They must select a row based on the id, and then another random one not including the row just selected. I currently have:

$query = $pdo->prepare('SELECT title, content FROM cards WHERE card_id=? LIMIT 1');
$query->execute([$slugId]);
$row = $query->fetch();

to select the row based on the id. But I am unsure how to get a random id, in that how do I go about it? Do I just do something along the lines of:

$randomQuery = $pdo->('SELECT title, content FROM cards ORDER BY RAND() WHERE card_id !=? LIMIT 1');
$randomQuery->execute([$slugId]);
$randomRow = $query->fetch();

or is there another way to do it? Because isn't using $pdo twice opening two connections to the database? Is this the correct way to do it or is there another way that will only use one connection?

TIA

Why not use AND?

Why not use AND?

niche1, because AND searches for rows that meet muliple conditions separated by an AND clause. It doesn't retrieve the result set of multiple queries.

What you can do, however, is use the UNION clause.

SELECT title, content
FROM cards
WHERE card_id = $card_id
LIMIT 1
UNION ALL
SELECT title, content
FROM cards
WHERE card_id <> $card_id
ORDER BY RAND()
LIMIT 1

@Dani, Thank you for your help. UNION was one of those things I read about when I first started with MySQL so I think it now requires a revisit from me. It will help a great deal now that I've seen it used in a 'real use' example and should make a lot more sense this time around.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.