-2

I know that in SQL if I wrote

SELECT EXISTS(SELECT 1 FROM userdata WHERE user_id=2);

SQL returned a 1 if it managed to select and a 0 if not.

+------------------------------------------------+
| EXISTS(SELECT 1 FROM userdata WHERE user_id=2) |
+------------------------------------------------+
|                                              1 |
+------------------------------------------------+

How would I check this in a PHP? I am using MySQLi. I want the code to look something like this…

    $selectbruh = SELECT EXISTS(SELECT 1 FROM userdata WHERE user_id=2);

    if(select returned 1){
        //Do this
    }else if(returned 0){
        //Do this
    }else{
        //Explode into smithereens
    }
TwoStraws
  • 12,862
  • 3
  • 57
  • 71

1 Answers1

1

People are confused because you've taken a… well… unorthodox approach, both with your SQL and with posting your code. You've said that you're using MySQLi, so here is the answer you're looking for:

$query = $db->query('SELECT 1 FROM userdata WHERE user_id = 2;');

if ($query->num_rows) {
    echo "Query returned 1\n";
} else {
    echo "Query returned 0\n";
}

It looks to me like you're trying to validate whether a user ID exists or not, in which case the results are either "exists" (1) or "doesn't exist" (0). There is no room for //Explode into smithereens, which I believe is a good thing :)

TwoStraws
  • 12,862
  • 3
  • 57
  • 71
  • HAHA Thanks, I didnt realise it would be soo simple! –  Dec 18 '15 at 14:43
  • Ok. So people have convinced me to use PDO instad of mysqli so how I do the same in PDO. –  Dec 20 '15 at 12:23
  • Please ask new questions as new questions, otherwise they are not discoverable for others. – TwoStraws Dec 20 '15 at 12:24
  • I cant ask another question. I have to wait 2 days or something –  Dec 20 '15 at 12:27
  • Well, OK. I don't like answering like this, but I also don't want to leave you hanging. So, you want something like this: `$query = $db->query('SELECT 1 FROM userdata WHERE user_id = 2;'); if ($query->fetchColumn()) { echo "Query returned 1\n"; } else { echo "Query returned 0\n"; }` – TwoStraws Dec 20 '15 at 12:31