如果字段为空,则实现子句

时间:2011-07-12 20:36:24

标签: php

我有以下代码在填写表单时从数据库返回行。问题是除非填写所有三个字段(名称,地址,类型),否则代码不会返回任何内容。我想更改代码,以便如果只说填写一个字段,它将只搜索那一个字段。

我感谢另一位成员的帮助,但我想我可能错了:

if (empty($name)) {
$nameClause='';
} else {
$nameClause="name='".$name."'";
}

.....

<?php
require("db_access.php");

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
return $xmlStr; 
} 

$name=$_POST['name'];
$address=$_POST['address'];
$type=$_POST['type'];



// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}




// Select all the rows in the markers table
$query = sprintf(
   "SELECT * FROM markers WHERE name = '%s' AND address = '%s' AND type = '%s'",
   mysql_real_escape_string($name),
   mysql_real_escape_string($address),
   mysql_real_escape_string($type)
);
$result = mysql_query($query);
if($result == false) {
   die(mysql_error() . "<br />\n$query");
}
if(mysql_num_rows($result) == 0) {
   user_error("No rows returned by:<br />\n$query");
} 

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'type="' . parseToXML($row['type']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

?>

我替换了这个:

$query = sprintf(
"SELECT * FROM markers WHERE name = '%s' AND address = '%s' AND type = '%s'",
mysql_real_escape_string($name),
mysql_real_escape_string($address),
mysql_real_escape_string($type)
);

有了这个:

$query = sprintf(
   "SELECT * FROM markers WHERE name = '%s' AND address = '%s' AND type = '%s'",
   mysql_real_escape_string($name),
   mysql_real_escape_string($address),
   mysql_real_escape_string($type)
);
$result = mysql_query($query);
if($result == false) {
   die(mysql_error() . "<br />\n$query");
}
if(mysql_num_rows($result) == 0) {
   user_error("No rows returned by:<br />\n$query");
} 

1 个答案:

答案 0 :(得分:1)

$query = sprintf(...)代码替换为:

$inputs = array('name', 'address', 'type');
$where  = array();

foreach($inputs as $input)
{
    if(!empty($_POST[$input])) {
        $where[] = "{$input} = '" . mysql_real_escape_string($_POST[$input]) . "'";
    }
}

if ($where) {
    $query = 'SELECT * FROM markers WHERE ' . implode(' AND ', $where);
} else {
    // do something here if name, address and type are all empty 
}