我想写的代码有点问题:
代码的目的是检查两个字段是否与表中的行匹配(两个字段已在代码中预定义,因此field1和field2)。如果它们匹配,则在HTML表格中显示该行中的其余信息。如果两个字段不匹配,则回显一条消息。
以下是我到目前为止的内容:
### 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包含:
### 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>");
非常感谢任何帮助。
答案 0 :(得分:2)
check_data.php中的代码似乎不完整。我希望有类似的东西:
$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
}
顺便说一下,你应该小心,因为这个代码可能导致SQL注入攻击,正如@AndrewLeach指出的那样。
答案 1 :(得分:0)
您的查询似乎正确。如果没有匹配,它将返回零行,因此您可以使用:
if (mysql_num_rows(mysql_query($check) > 0) {
//yes, fields match
} else {
//nop, fields don't match
}
如果您需要匹配的数据,请使用如下:
$handle = mysql_query($check);
$result = mysql_fetch_assoc($handle);
if ($result) {
echo $result['name']; //'name' is one of the table columns
} else {
//no result
}