确定在php中调用函数的位置

时间:2014-11-19 12:55:09

标签: php mysql

我试图像这样调用我的方法:

<?php getalluser($catid);?>

我的getalluser()方法中有一个select查询:

function getalluser($query)
{
  $sql = "SELECT * from user where catId='".$query."'";
}

在另一个页面中,我调用相同的方法并传递用户ID而不是类别ID,如下所示:

<?php getalluser($userID);?>

现在,我如何识别$ query中是否有类别ID或用户ID,因此我可以根据我的$ query更改where where condition。

4 个答案:

答案 0 :(得分:2)

添加另一个参数,来自。

选项应该是:

Users
Categories

function getalluser($query, $calledFrom = '')
{
  if ($calledFrom == 'users') {
    $sql = "SELECT * from user where catId='".$query."'";
  }
  if ($calledFrom == 'categories') {
   // SQL for fetching categories.
  }
}

并调用函数:

<?php getalluser($catid, 'users');?>
<?php getalluser($catid, 'categories');?>

答案 1 :(得分:0)

您可以使用debug_backtrace function。有了这些信息,你就会知道它的文件/功能是什么。

答案 2 :(得分:0)

&#34;两者都是整数&#34; 你可以跟随kfirba提示,或者你可以添加另一个默认为

的param
function getalluser($query, $user = "")
{
  if($user == ''){
  $sql = "SELECT * from user where catId='".$query."'";
  } else {
   // Query for users
  }
}

Cat电话:

<?php getalluser($catid);?>

用户来电:

<?php getalluser('', $userid);?> // example with first param empty

答案 3 :(得分:0)

如果你真的希望,你可以这样做

function getUserById($id, $searctype='catId') {

    // Use this to prevent anything other than userId and catId from being entered
    $types = array("catId", "userId");
    $searchtype = (in_array($searctype, $types) ? $searchtype:"catId";

    $sql = "SELECT * from user where ".$searchtype."='".$id."'";
}

然后调用`getUserById($ userId,&#34; userId&#34;);

注意:请查看使用PDO。这是处理SQL&amp; S的一种更安全的方式。有助于防止SQL注入。