0

Hi I've been trying to solve this for days so hopefully someone knows the answer.

At the top of my script I dynamically set a variable like so: $p_id = $_GET['p_id'];

I have then attempted to pass this variable to the following function in three different ways without any luck.

1)

public function Insert_Update($uid,$update,$uploads,**$p_id**) 
{
.....        

$query = mysql_query("INSERT INTO `messages` (message, uid_fk, poster_id,ip,created,uploads) VALUES ('$update', '$uid',
**'$p_id'**, '$ip','$time','$uploads')") or die(mysql_error());....

Interestingly, this approach works for the variable if I change the order of the arguments to ($p_id,$uid,$update,$uploads), however the other three variables become invisible to the function.

2)

public function Insert_Update($uid,$update,$uploads) 
{...

     // ... global **$p_id**;

        $query = mysql_query("INSERT INTO `messages` (message, uid_fk, poster_id,ip,created,uploads) VALUES ('$update', '$uid',
        **'$p_id'**, '$ip','$time','$uploads')") or die(mysql_error());....

3)

public function Insert_Update($uid,$update,$uploads) 
{
     ....
      //  $query = mysql_query("INSERT INTO `messages` (message, uid_fk, poster_id,ip,created,uploads) VALUES ('$update', '$uid',
     '".$_REQUEST[**'p_id'**]."', '$ip','$time','$uploads')") or die(mysql_error());...

No matter what approach I try the function never sees the variable. Any ideas? Thanks

4

2 回答 2

2

而不是仅仅使用$p_id = $_GET['p_id'];,首先确保它$_GET['p_id']有一个值。试试下面的代码:

$p_id = isset($_GET['p_id'])? $_GET['p_id'] : "some default value";

或者,如果您想在未设置变量的情况下引发错误,请尝试以下操作:

if(isset($_GET['p_id']))
{
    $p_id = $_GET['p_id'];
}
else
{
    echo "Please set 'p_id' and try again.";
    exit();
} 

此外,作为一般经验法则,如果可能,请避免在函数中使用与外部定义相同的变量名。例如,在您的函数中尝试命名它$pid而不是$p_id,因为这也是在您的函数之外使用的变量。

编辑 而不是定义$p_id为常量,然后将其添加到$GLOBALS数组中,然后将其传入,只需确保$p_id已设置,然后将其传入。例如:

$p_id = isset($_GET['p_id'])? $_GET['p_id'] : 2;

public function Insert_Update($uid,$update,$uploads,$pid) 
{
.....        

$query = mysql_query("INSERT INTO `messages` (message, uid_fk, poster_id,ip,created,uploads) VALUES ('$update', '$uid',
'$pid', '$ip','$time','$uploads')") or die(mysql_error());....
}

Insert_Update(1, "some text", "some file", $p_id);
于 2012-06-17T01:17:13.403 回答
1

您只是通过创建一个新变量来浪费内存。

$_GET['p_id']可以在任何范围内访问,因此无论您在何处访问它都会自动可见。这比尝试将常规变量传递给它要容易得多。

于 2012-06-17T01:09:48.027 回答