我试图在 MySQL 语句中将两个变量传递给 ORDER BY $variable1 $variable2 。变量是从下拉菜单表单中获取的。
PHP
if(isset($_POST['order'])){
$sort1 = mysql_real_escape_string($_POST['sort']);
$sort2 = mysql_real_escape_string($_POST['order']);
}
if(!@$_POST['order']){
$sort1 = 'ID';
$sort2 = 'DESC';
}
$topics = mysql_query(" SELECT topic_id AS 'ID', topic_head AS 'Title',
topic_tags AS 'TAGS', topic_owner AS 'CREATED BY', topic_date AS 'CREATED ON'
FROM forum_topics
ORDER BY '{$sort1}' '{$sort2}' ") or die (mysql_error());
?>
HTML 表格
<ul class="sort">
<li><form action="topics.php" method="post">
<label class="label">Sort Table By</label>
<select name="sort">
<option value =""> </option>
<option value ="ID">ID</option>
<option value ="Title">Title</option>
<option value ="TAGS">TAGS</option>
<option value ="VIEWS">VIEWS</option>
<option value ="CREATED ON">CREATED ON</option>
<option value ="CREATED BY">CREATED BY</option>
</select>
<label class="label">Order By</label>
<select name = "order" class="tap_Select">
<option value =""> </option>
<option value ="ASC">Ascending</option>
<option value ="DESC">Descending</option>
</select>
<input type="submit" name="order" value="SORT" >
</form>
</li>
</ul>
请帮忙。
更新
当我删除 $sort1 和 $sort2 周围的引号时
我收到此错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SORT' at line 4
更新 2
当我做 $sql = "....." 时,没有通过 mysql_query() 我得到了这个
SELECT topic_id AS 'ID', topic_head AS 'Title', topic_tags AS 'TAGS', topic_owner AS 'CREATED BY', topic_date AS 'CREATED ON' FROM forum_topics ORDER BY ID SORT