-1

我有以下代码不起作用。它不起作用,因为它会进行查询

WHERE 列 = ' * ',而不是WHERE 列 = *

我试图想出一种方法来获取它,因此如果在表单中发布了变量,它将执行 WHERE variable = 'var',如果未发布,则执行 WHERE 列 = *,但我想不出办法,以及我所做的一切尝试过是hacky或不起作用。

    if(isset($_POST['variable'])){
    $variable=$_POST['variable'];
    }
    else{$variable='*';}
    $sql="SELECT * FROM table WHERE column = '$variable'";

编辑,这是实际的代码:

<form method='post' action='policy.php?go'>
<input type='radio' name='gen' value='M'>Male
<input type='radio' name='gen' value='F'>Female
<select name='state'>
<option value='AK'>AK</option>
<option value='WY'>WY</option>
</select> 
<input type='radio' name='logic' value='>'>Older Than
<input type='radio' name='logic' value='<'>Younger Than
<select name='age'>
<option value='5'>5</option>
<option value='11'>11</option>
<option value='17'>17</option>
<option value='65'>65</option>
</select> 
<input type='submit' name='submit' value='Search'>
</form>
<?php 
if(isset($_GET['go']) && isset($_POST['submit'])){
if(isset($_POST['state'])){
$state="'".mysql_real_escape_string( $_POST['state'] )."'";
}
else{ $state='*';}
if(isset($_POST['age'])){
$age=$_POST['age'];
//append to query string
}
if(isset($_POST['logic'])){
$log=$_POST['logic'];
//append to query string
}
else{$log='';}
if(isset($_POST['gen'])){
$gen="'".mysql_real_escape_string( $_POST['gen'] )."'";
}
else {$gen='*';}
echo "<table id='hor-minimalist-b' summary='Employee Pay Sheet' class='tablesorter'>
<caption>Age: ".$log." ".$age." Gender: ".$gen." </caption>
<thead>
<tr>
<th scope='col'>State</th>
<th scope='col'>Number</th>
</tr>
</thead>
<tbody>";
// (WHY IS THIS NOT WORKING?)
$sql = "SELECT SUM(num) AS sum, state,gen,age FROM `policy-ssi` 
WHERE age $log $age AND gen = $gen
GROUP BY state
ORDER BY sum DESC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
4

1 回答 1

0

在 MySQL 中,字符串的通配符是%而不是*. 为了匹配该字段而不考虑其中的内容,请更改else {$gen='*';}else {$gen='\"%\"';}

此外,为了使用通配符,您的查询应该变成

$sql = "SELECT SUM(num) AS sum, state,gen,age FROM `policy-ssi` 
WHERE age $log $age AND gen LIKE $gen
GROUP BY state
ORDER BY sum DESC";
于 2013-05-04T23:32:20.353 回答