我有这段代码:
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
?>
目标是搜索我的mysql数据库,在其中一个字段中查找$_POST['clientsearch']
的结果,并返回包含该字的行(它总是1个字)
如果我使用它:
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."'"")
它似乎有效。但它只搜索FNAME列,而不是所有列。我也只得到第一个结果。不是全部。
我正在启动php / mysql,所以我有点迷失,还不知道所有功能。有人可以解释我如何修复我的代码吗?
非常感谢您的帮助:)
答案 0 :(得分:1)
对于初学者,如果您期望超过1行,则需要遍历结果集中的每一行。我将用原始代码说明如何执行此操作。
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// Print out the contents of the entry for each row in result
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
}
?>
在mysql_real_escape_string
上查看有关注入内容的初学者的PHP文档。
另外,正如其他人所说,您可能正在寻找LIKE
而不是=
SQL语法。另外,请查看%
的{{1}}外卡。
答案 1 :(得分:0)
不是问题的答案,但希望有帮助。尝试编写如下代码:
$cs = mysql_escape_string($_POST['clientsearch']);
$result = mysql_query("
SELECT
*
FROM clients
WHERE
FNAME='$cs'
OR LNAME='$cs'
OR MAIL='$cs'
OR TEL='$cs'
");
你的缩进究竟是由你决定的。这种方法有助于提高可读性,因此也有助于调试:)