谁能看到我在这里做错了什么?我正在尝试根据数据库中字段的值包含某个页面。
我有 2 张桌子要检查,
如果用户名出现在表.1 中,并且字段单位 = 天,包括天.php
如果用户名出现在表.1 中,并且字段.单位 = 小时,包括小时.php
如果用户名出现在表.2 中,并且字段单位 = 天,包括天.php
如果用户名出现在表.2 中,并且字段.单位 = 小时,包括小时.php
$username = $USER->firstname.' '.$USER->lastname;
echo $username;
$is_academic_result = mysql_query('SELECT * from holiday_entitlement_academic where employee = '.$username.'');
$is_business_result = mysql_query('SELECT * from holiday_entitlement_business_manual where employee = '.$username.'');
if(mysql_num_rows($is_academic_result) > 0){
while($is_academic = mysql_fetch_array($is_academic_result)) {
if ($is_academic['units'] == 'days'){include('days.php');}
else if ($is_academic['units'] == 'hours'){include('hours.php');}
}
}
else if(mysql_num_rows($is_business_result) > 0){
while($is_business = mysql_fetch_array($is_business_result)) {
if ($is_business['units'] == 'days'){include('days.php');}
else if ($is_business['units'] == 'hours'){include('hours.php');}
}
}
首先,您不需要在while
循环中执行任何这些操作,因为只会返回一个或零个结果(您正在检查主键,对吧?
其次,您的查询设置不正确 - 您使用的是单引号,但从未转义它们。
因此,考虑到这一点,我们执行以下操作:
$is_academic_result = mysql_query('SELECT * from holiday_entitlement_academic where employee = '' . $username . ''');
$is_business_result = mysql_query('SELECT * from holiday_entitlement_business_manual where employee = '' . $username . ''');
if($is_academic = mysql_fetch_array($is_academic_result)) {
switch($is_academic['units']) {
case 'days':
include_once('days.php');
break;
case 'hours':
include_once('hours.php');
break;
default:
break;
}
} else if ($is_business = mysql_fetch_array($is_business_result)) {
switch($is_business['units']) {
case 'days':
include_once('days.php');
break;
case 'hours':
include_once('hours.php');
break;
default:
break;
}
}
请注意,您应该停止使用mysql_*
函数。它们正在被弃用。而是使用 PDO(从 PHP 5.1 开始支持)或 mysqli(从 PHP 4.1 开始支持)。如果您不确定要使用哪一个,请阅读这篇 SO 文章。
编辑 如果您不确定问题出在哪里,您可以随时echo
查询,以确保将您认为要传递的内容传递给数据库(通常情况下,当查询不起作用时,要么是这个,要么是你的逻辑不好)。
如果您的用户名确实包含
(这似乎是一个糟糕的设计),那么您在查询中$username
周围缺少引号。 就像你现在一样,存在语法问题,你在末尾留下一个引号,根本不引用$username
。
// Use double quotes on the string, and single around $username
$is_academic_result = mysql_query("SELECT * from holiday_entitlement_academic where employee = '$username'");
// Same thing...
$is_business_result = mysql_query("SELECT * from holiday_entitlement_business_manual where employee = '$username'");
如果对结果资源进行一些错误检查,则会发现这些问题:
if (!$is_academic_result) {
// Query problem
echo mysql_error();
}
// Same for the other query...