0

After a search here I couldn't see anyone with the same (strange) problem as me. I have a very simple task which is to check whether some name already exists on a table, but the thing is the mysql_num_rows is returning wrong values.

I'm sorry, I forgot to mention that this only happens when I try to look for words with special chars. Bebês, Câmeras, Calção are examples.

$sql = "
    SELECT cattitle as category
    FROM categories
    WHERE cattitle = '$title'
";
$res = mysql_query($sql, $con) or die(mysql_error());
$num = mysql_num_rows($res);

I even have tried with mysql_result

$sql = "
    SELECT count(cattitle) as category
    FROM categories
    WHERE cattitle = '$title'
";
$res = mysql_query($sql, $con) or die(mysql_error());
$num = mysql_result($res,0);

The worst thing is, when I run the query directly, I get the correct results ($num > 0). I'm not that experienced programmer and, at first, I thought it was returning values from other queries, but I've checked and changed the name of those vars and the problem persisted.

Could be some kind of conflict? Can someone help me with this error? Kind regards,

  • Before you continue, get a more modern book about PHP, the code is more than 5 years behind. – Marek Nov 13 '13 at 13:05

2 Answers2

0

Your example is basic one, and it should work. It is even in PHP manual as example.

Try this way:

$sql = "
    SELECT cattitle
    FROM categories
    WHERE cattitle = '$title'
    LIMIT 1
";
$res = mysql_query($sql, $con) or die(mysql_error());
if ($row = mysql_fetch_assoc($res)) {
    # category already exists, do smth?
}
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • I'm sorry, I forgot to mention that this only happens when I try to look for words with special chars. When I look for "normal" chars, my examples work perfectly (so as yours). –  Nov 13 '13 at 13:44
  • @GabrielSoaresMiranda: then you probably have encoding problem, take a look at this link > http://stackoverflow.com/questions/279170/utf-8-all-the-way-through – Glavić Nov 13 '13 at 13:58
0

I think your problem may be in wrong charsets for your mysql database and for string in your PHP script.

When you use mysql console then it convert symbols in correct charset.

Check charset and collate for your table and field cattitle.

Best solution will change it to UTF8

Also use UTF8 when write your script

newman
  • 2,689
  • 15
  • 23