我有这样的代码:
<?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,所以我有点迷路了,还不知道所有的函数。有人能解释一下我如何修复我的代码吗?
非常感谢您的帮助:)
发布于 2012-03-02 03:34:34
对于初学者来说,如果需要超过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语法。另外,请查看LIKE的%通配符。
发布于 2012-03-02 03:33:33
不是这个问题的答案,但希望能有所帮助。试着像这样写代码:
$cs = mysql_escape_string($_POST['clientsearch']);
$result = mysql_query("
SELECT
*
FROM clients
WHERE
FNAME='$cs'
OR LNAME='$cs'
OR MAIL='$cs'
OR TEL='$cs'
");缩进的方式由你自己决定。这种方法对可读性有很大帮助,因此也有助于调试:)
https://stackoverflow.com/questions/9522572
复制相似问题