I have a bit of an issue with a code I am trying to write:
The purpose of the code is to check if two fields match from a row in a table (the two fields have already been pre-defined in the code, so field1 and field2). If they do match it displays the rest of the information in that row in a HTML table. If the two fields do not match then it echo's a message.
Below is what I've got so far:
### Connects to db
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'dbname';
mysql_select_db($dbname);
echo ("<table width=\"580px\" class=\"board\" border=\>
<form method=\"post\" action=\"check_data.php\">
<tr>
<td>Field1</td>
<td>
<input type=\"text\" name=\"f1\"
size=\"20\">
</td>
</tr>
<tr>
<td>Field 2</td>
<td>
<input type=\"text\" name=\"f2\" size=\"40\">
</td>
</tr>
<tr>
<td align=\"right\">
<input type=\"submit\"
name=\"submit value\" value=\"Check\">
</td>
</tr>
</form>
</table>")
Check_data.php contains:
### Connects to db
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'dbname';
mysql_select_db($dbname);
$id = $_POST['f1'];
$points = $_POST['f2'];
## Query
$check = "SELECT * FROM table WHERE `field1` = '$f1' AND `field2` = '$f2'";;
mysql_query($check);
echo("<div class=\"successful\">Field 1 and Field 2 match.
$check</div>");
Any help would be greatly appreciated.
The code in check_data.php seems incomplete. I'd expect something like:
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'dbname';
if (!mysql_connect($dbhost, $dbuser, $dbpass)) {
die('Not connected : ' . mysql_error());
}
if (!mysql_select_db($dbname)) {
die ('Can\'t use foo : ' . mysql_error());
}
$id = $_POST['f1'];
$points = $_POST['f2'];
$check = "SELECT * FROM table WHERE `field1` = '$id' AND `field2` = '$points'";
$res = mysql_query($check);
if (!$res) {
die('Invalid query: ' . mysql_error());
}
if( mysql_num_rows($res) > 0 ){
// fields match
} else {
// fields don't match
}
By the way, you should be careful, because this code could lead to SQL injection attacks, as @AndrewLeach pointed out.
Your query seems right. It will return zero rows if there aren't matches, so you can use:
if (mysql_num_rows(mysql_query($check) > 0) {
//yes, fields match
} else {
//nop, fields don't match
}
If you need data from the match, use like this:
$handle = mysql_query($check);
$result = mysql_fetch_assoc($handle);
if ($result) {
echo $result['name']; //'name' is one of the table columns
} else {
//no result
}