我正在尝试使用以下代码。我的目标是显示一个id ='$ id'的页面。但是,如果$ id的值为空,我想在我的数据库中显示最新的条目。
<?php
mysql_connect("localhost", "root", "password");
mysql_select_db("database");
if(!(isset($_GET['id']))){
$query = mysql_query("SELECT * FROM mytable WHERE name='somename' ORDER BY id DESC LIMIT 1");
while($var1 = mysql_fetch_assoc($query)){
$y = $var1['id'];
}
}
mysql_data_seek($query, 0);
$id = (isset($_GET['id'])) ? (int)$_GET['id'] : '$y';
$query1 = mysql_query("SELECT * FROM mytable WHERE id='$id'");
while($query_row = mysql_fetch_assoc($query1)){
//some code
}
?>
问题是当$ id没有值时,首先执行循环。但第二个while循环不起作用。有人请告诉我一个解决方案
答案 0 :(得分:0)
尝试删除第一个if语句
周围的括号if(!isset($_GET['id'])){
$query = mysql_query("SELECT * FROM mytable WHERE name='somename' ORDER BY id DESC LIMIT 1");
while($var1 = mysql_fetch_assoc($query)){
$y = $var1['id'];
}
}
答案 1 :(得分:0)
试试此代码
<?php
mysql_connect("localhost", "root", "password");
mysql_select_db("database");
$query = mysql_query("SELECT * FROM mytable WHERE name='somename' ORDER BY id DESC LIMIT 1");
$var1 = mysql_fetch_assoc($query);
$y = $var1['id'];
$id = (isset($_GET['id'])) ? $_GET['id'] : $y ;
$query1 = mysql_query("SELECT * FROM mytable WHERE id='$id'");
while($query_row = mysql_fetch_assoc($query1)){
//some code
}
?>
答案 2 :(得分:0)
尝试
$query1 = mysql_query("SELECT * FROM mytable WHERE id='".$id."'");
而不是
$query1 = mysql_query("SELECT * FROM mytable WHERE id='$id'");
此外,清理您的数据以避免SQL注入攻击并使用PDO。