Reputation: 99
I stuck on something stupid.. I have the table that has only one column. I want to check if there is some value, which I get from the url (method $_GET)
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$row=htmlspecialchars($_GET['row']);
$query = @mysql_query ("SELECT * FROM table WHERE row=$row");
if ($result = @mysql_fetch_array($query)) {
echo "There is that row";
}
else {
echo "There is not that row";
}
Can you tell me what's wrong?
Upvotes: 0
Views: 98
Reputation: 11665
The correct way would be to check if the resultset contains any rows. You can do this with mysql_num_rows():
if (mysql_num_rows($query)>0) {
echo "There is that row";
}
else {
echo "There is not that row";
}
Also if your $row
is a string, you should enclose it in single quotes.
Please, don't use mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Upvotes: 1
Reputation: 3442
You seem to mix row and column. When querying SQL database you usually specify clumnName="value"
after WHERE statement. You have valid syntax for a table with one column named "row".
There might be a problem in your query as you do not escape your arguments, so it will fail it $row actually has any quotes in it. This would be avoided with use of PDO instead of mysql_
functions which are no longer maintained. Query your table like this instead:
$query = @mysql_query("SELECT * FROM gvar WHERE gvarebi='{addslashes($row)}'");
To actually check if there are any results, it is better to use mysql_num_rows
as it will return number of rows for specified query. So update your code with this:
if (mysql_num_rows($query) > 0) {
echo "row exists";
} else {
echo "row does not exists";
}
Upvotes: 0
Reputation: 1402
Obligatory "you should be using PDO" comment.
You don't say what sort of field it is, maybe it is a text field so it needs to be in quotes.
$query = @mysql_query ("SELECT * FROM table WHERE row='" . $row . "');
Also if you remove the @ you might get to see some sort of error
$query = mysql_query ("SELECT * FROM table WHERE row='" . $row . "') or die(mysql_error());
Upvotes: 0