请先查看此代码:
$dbhost = xxxx;
$dbuser = xxxxxxx;
$dbpass = xxxxxxxxx;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$sql = SELECT week, name, date FROM lucky;
$sqlx = SELECT week, name, date FROM lucky WHERE week = 1;
$sqlxx = SELECT week, name, date FROM lucky WHERE week = 2;
$retval = mysql_query( $sqlx, $conn );
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$fetch = $_POST['weekcheck'];
if($fetch == 1)
{
echo "{$row['week']}";
}
}
此代码中 weekcheck 的值来自不同的页面。我想要的只是,如果 $ fetch == 1 ,那么我想运行 $ sqlx ,如果 $ fetch == 2 ,那么我想要运行 $ sqlxx 。但在 $ retval 中,已使用 $ sqlx 。请提出建议。
答案 0 :(得分:0)
if(!empty($_POST['weekcheck'])) // check whether its not blank
{
$where = " where `week` =".$_POST['weekcheck'];
}
else
{
$where = ""; // blank string
}
// so if weekcheck is posted then what ever the value is will pass to the sql query.
//for e.g. $_POST['weekcheck']=1;
//then sql statement will be SELECT week, name, date FROM lucky where `week` = 1
//for e.g. $_POST['weekcheck']=2;
//then sql statement will be SELECT week, name, date FROM lucky where `week` = 2
//else if not posted weekcheck
//then sql statement will be SELECT week, name, date FROM lucky
$sql = "SELECT week, name, date FROM lucky ".$where;
$retval = mysql_query( $sqlx, $conn );
你从这里得到它..! :)
答案 1 :(得分:0)
试试这个
$sql = SELECT week, name, date FROM lucky;
$sqlx = SELECT week, name, date FROM lucky WHERE week = 1;
$sqlxx = SELECT week, name, date FROM lucky WHERE week = 2;
$retval = mysql_query( $sqlx, $conn );
$retvalxx = mysql_query( $sqlxx, $conn );
$fetch = $_POST['weekcheck'];
if($fetch == 1)
{
while($row3 = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//do some thing
}
}
if($fetch == 2)
{
while($row2 = mysql_fetch_array($retvalxx, MYSQL_ASSOC))
{
//do some thing
}
}
答案 2 :(得分:0)
没有测试此代码,但它应该运行,它还会清理你的周检查整数
<?php
$dbhost = xxxx;
$dbuser = xxxxxxx;
$dbpass = xxxxxxxxx;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$one_and_only_sql = "SELECT week, name, date FROM lucky".(intval($_POST['weekcheck'])>0)?" WHERE week =".(intval($_POST['weekcheck'])):"";
$retval = mysql_query( $one_and_only_sql, $conn );
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['week']}";
}
?>
回复你的评论:
将$ one_and_only_sql的行替换为:
$one_and_only_sql = "SELECT week, name, date FROM lucky".(intval($_POST['weekcheck'])>0)?" WHERE week = 'Week ".str_pad(strval(intval($_POST['weekcheck'])), 2, "0", STR_PAD_LEFT)." 2014'":"";