I'm trying to do a seat booking system, and i need to check via MySQL if the seat X is available. If there is a name assigned to it, print "sorry, this seat is already taken", else if there is no name assigned to it (default 0), print "available!".
This is what i tried:
<?php
$link = mysql_connect(localhost, root, root);
mysql_select_db(room);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$result = mysql_query("SELECT name FROM seats WHERE seat = 'A1'");
if ($result == '0') {
echo 'available!';
} else {
echo 'Sorry, this seat is already taken.';
}
}
?>
You should considered moving away from the mysql_* functions. Either way, you should be doing something like this:
http://php.net/manual/en/function.mysql-num-rows.php
$result = mysql_query("SELECT name FROM seats WHERE seat = 'A1'");
if (mysql_num_rows($results) == 0) {
echo 'available!';
} else {
echo 'Sorry, this seat is already taken.';
}
You've also got an extra }
at the end.
Try this :
$result = mysql_query("SELECT name FROM seats WHERE seat = 'A1'");
if (mysql_num_rows($result)==0) {
echo 'available!';
}else {
echo 'Sorry, this seat is already taken.';
}
Try this:
<?php
$link = new mysqli("localhost", "root", "root", "room");
if ($link->connect_errno)
{
die('Could not connect: ' . $mysqli->connect_error);
}
if (($result = $link->query("SELECT name FROM seats WHERE seat = 'A1'") && $result->num_rows)
{
echo 'Sorry, this seat is already taken.';
}
else
{
$result->close();
echo 'available!';
}
This is using the new MySQLi library and should properly check whether a result was returned with any rows. Checking $result->num_rows
may not be necessary, as $result
should be empty if no rows were returned.