0
$stmt = $db->prepare("SELECT * FROM user WHERE name='Steve Job'");
$stmt->execute();
if($stmt->num_rows){
    echo "1";
}

it return blank in my ajax callback. I've debugging for hours.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • And you are sure you have a record where `name = 'Steve Job'` – Incognito Feb 17 '14 at 09:44
  • you missed `$stmt->store_result();` after the `$stmt->execute();` – ponciste Feb 17 '14 at 09:46
  • @ponciste already mentioned in my answer friend :) – Andy Holmes Feb 17 '14 at 09:47
  • Probably because his name is Steve _Jobs_ :-) In any case, you could probably get away with `select 1` or `select count(*)` so s to avoid all of Steve's information having to come across the wire. There are precious few situations where `select *` makes sense, detecting the existence of a row is certainly not one of them. – paxdiablo Feb 17 '14 at 09:49
  • @AndyHolmes yes, 20 seconds earlier :-) – ponciste Feb 17 '14 at 09:50
  • Haha sorry @ponciste didn't realise it was that close – Andy Holmes Feb 17 '14 at 09:51
  • 1
    @AndyHolmes no problem. Btw i marked your answer as useful – ponciste Feb 17 '14 at 09:52
  • @paxdiablo so instead of select all what you suggest? select name? – user3318525 Feb 17 '14 at 10:00
  • user3318525, I suggest `count(*)` - it should simply give you a single row holding a single value, no need to transfer a lot of stuff over the wire. This may become important when your DB server is a thousand kilometers away and there are ten million rows :-) – paxdiablo Feb 17 '14 at 10:16
  • Does this answer your question? [How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)](https://stackoverflow.com/questions/22252904/how-to-check-if-a-row-exists-in-mysql-i-e-check-if-an-email-exists-in-mysql) – Dharman Feb 14 '20 at 22:35

1 Answers1

1
$stmt = $db->prepare("SELECT * FROM user WHERE name='Steve Job'");
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;
if($numRows > 0){
    echo "1";
}

You need to use store_result before working with num_rows

Andy Holmes
  • 7,817
  • 10
  • 50
  • 83