Two queries from table at the same time

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

Check table to see if array items already exist

Hi all,

I have been confusing myself for days over this so bear with me if it gets a bit confusing.

I have a table called tags with columns id, name which list all unique tags (linux, php, mysql, etc.). And I have an array that includes some tags that have been entered:

$tags = array('linux,php,mysql');

Now when the array has just one tag I can search the tags table and return whether the tag already exists in the table or not. But I am unsure how I can go about checking for each array item. My thinking on how to go about this (and I could be wrong) is:

  1. Explode the array.
  2. Check the first item in the array to the table.
  3. If it does not exist, put it into a separate array.
  4. Once all items have been iterated, store these unique tags in the table.

For reference, currently I have:

function tagExists($pdo, $tag) {
  $stmtTagExists = $pdo->prepare('SELECT * FROM tags WHERE name=?');
  $stmtTagExists->execute([$tag]);
  return $stmtTagExists->fetch(PDO::FETCH_ASSOC);
}

$tags = array('linux');

foreach($tags as $item) {
        if (tagExists($pdo, $item)) {
          echo 'The tag ' . $item . ' exists! <br>';
        } else {
          echo 'The tag ' . $item . ' does not exist! <br>';
        }
      }

If you need any clarification on anything, just ask.

TIA