麻烦的mySQL查询。需要*代替'*'

时间:2013-05-04 21:41:42

标签: php mysql string escaping query-string

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

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

我试着想办法得到它所以它会做WHERE变量='var'如果变量在表单中发布而WHERE column = *如果没有发布,但我想不出办法,我尝试的一切都是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)) {

1 个答案:

答案 0 :(得分: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";