为什么我不能在 Drupal 中使用 PHP 函数?

发布于 2025-01-01 07:37:32 字数 11841 浏览 0 评论 0原文

我想通了!

@Marc B 建议我对我的文件使用 include_once(),而不是 include。这修复了我收到的错误。

但是,我仍然遇到验证功能无法正常运行的问题。我发现它没有将我的变量传递给函数。

显然,Drupal 的某些功能不允许函数通过简单地请求同一函数内的全局 $variables 来接收变量。我必须将 $variables 声明为函数外部的全局变量,其中 $variables 是我的数组。

下面的原始问题:



我创建了一个 PHP 文件,用于编辑数据库中公司的公司信息。当我访问 drupal 之外的页面时,一切都运行良好,但是当将其包含在 drupal 页面中(或者甚至将代码粘贴到 drupal 页面中)时,我会收到验证错误,因为它无法运行我的验证功能(或者如果我删除验证,我的流程函数不起作用),我可以注释掉这些函数并在 if(isset($_POST['submit'])) 之类的语句中调用我的流程脚本,并且它可以在Drupal,但是我想使用我的函数。

如果我在 Drupal 中编辑页面,我会看到以下错误:

致命错误:无法重新声明 validate()(之前在 /home/content/84/6649484/ 中声明) html/commons/profiles/drupal_commons/custom/editcompany/editcompany.php:416)在/home/content/84/6649484/html/commons/profiles/drupal_commons/custom/editcompany/editcompany.php 第 452 行

(416 是我在验证函数中调用第一件事的地方,452 是相同)

为什么在 Drupal 中包含 PHP 页面时无法使用函数?是什么导致我的函数挂起,有没有办法解决这个问题?这是我的代码:

<?php
//connect to database
include('db.php');



////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Validate   /   Process Form                ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

//set form variables
    $form['accountnumber'] = $_POST['accountnumber'];
    $form['companyname'] = $_POST['companyname'];
    $form['address'] = $_POST['address'];
    $form['address2'] = $_POST['address2'];
    $form['city'] = $_POST['city'];
    $form['state'] = $_POST['state'];
    $form['zip'] = $_POST['zip'];
    $form['beds'] = $_POST['beds'];



if(isset($_POST['submit'])) {

    //run the validate function
    $validated = validate();

    //if one of the validations returned false, let's declare $errors as true and we'll display a message
    if($validated[0] == false) {
        $v_errors = true;
    } else {
        $processed = process();

        //see if there were errors adding it to the database
        if($processed == false) {
            $db_errors = true;
        }

        if($processed == true) {
            $success = true;
        }
    }

}



?>





<?php
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Form                                       ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////


//choose company
?>

<form id="choosecompany" action="" method="get">


<?php

//get company from url
$company_id = $_GET['id'];



//get all active companies
$result = mysql_query("SELECT account_num AS 'a', name AS 'n', city AS 'c', state AS s FROM company_profiles WHERE type = 'Customer' ORDER BY name ASC");

?>

<select name="id" style="display: block; position: relative; margin: 5px auto;">

    <?
    while($row = mysql_fetch_array($result)) {
        ?>

        <option value="<?php echo $row['a']; ?>" <?php if($row['a'] == $company_id) { echo 'selected="selected"'; } ?>>
        <strong><?php echo  $row['n'] 
        . ' - ' . $row['c'];
        if($row['c']) { echo ', '; }
        echo $row['s']; ?></strong>
        <?php echo ' (' . $row['a'] . ')';?></option>

        <?php
    }
    ?>

</select>

<input type="submit" name="submit" value="Edit" style="display: block; position: relative; margin: 0 auto;" />


</form>


<?php
if($company_id) {
    //get company info from db
    $result = mysql_query("SELECT * FROM company_profiles WHERE account_num = '$company_id'");

    while($row = mysql_fetch_array($result)) {
        $form['accountnumber'] = $row['account_num'];
        $form['companyname'] = $row['name'];
        $form['address'] = $row['address'];
        $form['address2'] = $row['address2'];
        $form['city'] = $row['city'];
        $form['state'] = $row['state'];
        $form['zip'] = $row['zip'];
        $form['beds'] = $row['beds'];
    }

}

?>





<form id="editcompany" action="" method="post">

    <h1>Edit Company</h1>

    <?php

    if($v_errors) {
        echo '<span id="errors"> Company not updated. Please enter required information.';
        echo '</span>';
    }

    if($db_errors) {
        echo '<span id="errors"> Company not updated. Please contact your system admin. </span>';
    }

    if($success) {
        echo '<span id="success"> Company information successfully updated. </span>';
    }

    ?>


    <ul id="block1">
        <li id="accountnumber">
            <label>Account #</label>
            <input readonly type="text" name="accountnumber" value="<?php echo $form['accountnumber']; ?>" <?php if($validated[1] == 'error') { echo 'class="error"'; } ?> />
        </li>


        <li id="companyname">
            <label>Company Name</label>
            <input type="text" name="companyname" value="<?php echo $form['companyname']; ?>" <?php if($validated[2] == 'error') { echo 'class="error"'; } ?> />
        </li>



        <li id="address">
            <label>Address</label>
            <input type="text" name="address" value="<?php echo $form['address']; ?>" />
            <input type="text" name="address2" value="<?php echo $form['address2']; ?>" />
        </li>




        <li id="csz">
            <label>City, State, Zip</label>
            <input id="city" type="text" name="city" value="<?php echo $form['city']; ?>" <?php if($validated[3] == 'error') { echo 'class="error"'; } ?> />

            <input id="state" type="text" name="state" maxlength="2" value="<?php echo $form['state']; ?>" <?php if($validated[4] == 'error') { echo 'class="error"'; } ?> />

            <input id="zip" type="text" name="zip" maxlength="5" value="<?php echo $form['zip']; ?>" />
        </li>


    </ul>



    <ul id="block2">
        <li id="products">
            <label>Products</label>
            <ul>
           <?php 

           //get all products from database
            $getproducts = mysql_query("SELECT id, name, url FROM products ORDER BY weight ASC");

            while ($rowproducts = mysql_fetch_array($getproducts)) {

                $product_id = $rowproducts['id'];
                $product_name = $rowproducts['name'];
                $product_url = $rowproducts['url'];

                $getuserhasproduct = mysql_query("SELECT DISTINCT product_id FROM products_accounts WHERE account_number = '$form[accountnumber]' AND product_id = '$product_id'");
                $user_has_product = mysql_num_rows($getuserhasproduct);

                if($user_has_product){
                    $hasproduct = true;
                }



            //list all products 
            ?>
                <li>
                    <label><?php echo $product_name; ?></label>
                    <input type="checkbox" name="<?php echo $product_id; ?>" value="TRUE" <?php if($user_has_product) { echo 'checked'; } ?> />
                </li>
            <?php



            //end while
            }
            ?>



            </ul>
        </li>


        <li id="demographics">
            <ul>
                <li id="beds">
                    <label>Beds</label>
                    <input type="text" name="beds" value="<?php echo $form['beds']; ?>" />
                </li>

            </ul>
        </li>


    </ul>


    <input type="submit" name="submit" value="Update" />


</form>





<?php
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Validate Function                          ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

function validate() {
    //get variables
    global $form;

    $v = true;

    //validate account number

    if(!$form['accountnumber']) {
        $v = false;
        $v1 = 'error';
    }

    if(!$newaccount) {
        $v5 = 'error';
    }

    //validate company name
    if(!$form['companyname']) {
        $v = false;
        $v2 = 'error';
    }

    //validate city
    if(!$form['city']) {
        $v = false;
        $v3 = 'error';
    }

    //validate state
    if(!$form['state']) {
        $v = false;
        $v4 = 'error';
    }

    $validated = array($v,$v1,$v2,$v3,$v4,$v5);
    return $validated;

}








////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Process Function                           ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

function process() {
    //get variables
    global $form;
    global $_POST;

    //set variables for clean entry into database
    $an = mysql_real_escape_string($form['accountnumber']);
    $n = mysql_real_escape_string($form['companyname']);
    $a = mysql_real_escape_string($form['address']);
    $a2 = mysql_real_escape_string($form['address2']);
    $c = mysql_real_escape_string($form['city']);
    $s = mysql_real_escape_string($form['state']);
    $z = mysql_real_escape_string($form['zip']);
    $b = mysql_real_escape_string($form['beds']);




    //get all products from database
            $getproducts = mysql_query("SELECT id, name, url FROM products ORDER BY weight ASC");

            while ($rowproducts = mysql_fetch_array($getproducts)) {

                $product_id = $rowproducts['id'];
                $product_name = $rowproducts['name'];
                $product_url = $rowproducts['url'];

                $getuserhasproduct = mysql_query("SELECT DISTINCT product_id FROM products_accounts WHERE account_number = '$form[accountnumber]' AND product_id = '$product_id'");
                $user_has_product = mysql_num_rows($getuserhasproduct);

                //if the user has the product, let's delete it if we need to delete it, otherwise leave it alone.
                if($user_has_product){

                    if($_POST[$product_id] == false) {
                        mysql_query("DELETE FROM products_accounts WHERE account_number = '$form[accountnumber]' AND product_id = '$product_id'");
                    }

                //if the user doesn't have the product, let's add it if we need to add it, otherwise leave it alone.
                } else {

                    if($_POST[$product_id] == true) {
                        mysql_query("INSERT INTO products_accounts (account_number, product_id) VALUES ('$form[accountnumber]', '$product_id')");
                    }
                }


            }




    $result = mysql_query("UPDATE company_profiles SET name = '$n', address = '$a', address2 = '$a2', city = '$c', state = '$s', zip = '$z', beds = '$b' WHERE account_num = '$an'");

    if(!$result) {
        $processed = false;
        die('Could not connect: ' . mysql_error());
    } else {
        $processed = true;
    }


    return $processed;

}



?>

I figured it out!

@Marc B suggested that I use include_once() for my file, rather than include. This fixed the error that I was receiving.

However, I still had the problem of my validation function not running correctly. I figured out that it wasn't passing my variables to the function.

Evidently, SOMETHING with Drupal doesn't allow a function to receive variables by simply requesting global $variables inside of same function. I had to declare the $variables to be global outside of the function, where $variables is my array.

Original Question Below:



I have a PHP file that I created to edit company information for companies in my database. Everything works beautifully when I access the page outside of drupal, but when including it in a drupal page (or even pasting the code into a drupal page, I get my validation errors because it can't run my validation function (or if i remove validation, my process function does not work). I can comment out the functions and call my process script in a statement like if(isset($_POST['submit'])), and it works within Drupal, but I'd like to use my functions.

If I go to edit for the page in Drupal, I see the following error:

Fatal error: Cannot redeclare validate() (previously declared in /home/content/84/6649484/html/commons/profiles/drupal_commons/custom/editcompany/editcompany.php:416) in /home/content/84/6649484/html/commons/profiles/drupal_commons/custom/editcompany/editcompany.php on line 452

(416 is where I call the first thing in my validate function, 452 is the closing of same)

Why can't I use functions when including a PHP page in Drupal? What is causing the hangup with my functions, and is there a way to fix this? Here's my code:

<?php
//connect to database
include('db.php');



////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Validate   /   Process Form                ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

//set form variables
    $form['accountnumber'] = $_POST['accountnumber'];
    $form['companyname'] = $_POST['companyname'];
    $form['address'] = $_POST['address'];
    $form['address2'] = $_POST['address2'];
    $form['city'] = $_POST['city'];
    $form['state'] = $_POST['state'];
    $form['zip'] = $_POST['zip'];
    $form['beds'] = $_POST['beds'];



if(isset($_POST['submit'])) {

    //run the validate function
    $validated = validate();

    //if one of the validations returned false, let's declare $errors as true and we'll display a message
    if($validated[0] == false) {
        $v_errors = true;
    } else {
        $processed = process();

        //see if there were errors adding it to the database
        if($processed == false) {
            $db_errors = true;
        }

        if($processed == true) {
            $success = true;
        }
    }

}



?>





<?php
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Form                                       ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////


//choose company
?>

<form id="choosecompany" action="" method="get">


<?php

//get company from url
$company_id = $_GET['id'];



//get all active companies
$result = mysql_query("SELECT account_num AS 'a', name AS 'n', city AS 'c', state AS s FROM company_profiles WHERE type = 'Customer' ORDER BY name ASC");

?>

<select name="id" style="display: block; position: relative; margin: 5px auto;">

    <?
    while($row = mysql_fetch_array($result)) {
        ?>

        <option value="<?php echo $row['a']; ?>" <?php if($row['a'] == $company_id) { echo 'selected="selected"'; } ?>>
        <strong><?php echo  $row['n'] 
        . ' - ' . $row['c'];
        if($row['c']) { echo ', '; }
        echo $row['s']; ?></strong>
        <?php echo ' (' . $row['a'] . ')';?></option>

        <?php
    }
    ?>

</select>

<input type="submit" name="submit" value="Edit" style="display: block; position: relative; margin: 0 auto;" />


</form>


<?php
if($company_id) {
    //get company info from db
    $result = mysql_query("SELECT * FROM company_profiles WHERE account_num = '$company_id'");

    while($row = mysql_fetch_array($result)) {
        $form['accountnumber'] = $row['account_num'];
        $form['companyname'] = $row['name'];
        $form['address'] = $row['address'];
        $form['address2'] = $row['address2'];
        $form['city'] = $row['city'];
        $form['state'] = $row['state'];
        $form['zip'] = $row['zip'];
        $form['beds'] = $row['beds'];
    }

}

?>





<form id="editcompany" action="" method="post">

    <h1>Edit Company</h1>

    <?php

    if($v_errors) {
        echo '<span id="errors"> Company not updated. Please enter required information.';
        echo '</span>';
    }

    if($db_errors) {
        echo '<span id="errors"> Company not updated. Please contact your system admin. </span>';
    }

    if($success) {
        echo '<span id="success"> Company information successfully updated. </span>';
    }

    ?>


    <ul id="block1">
        <li id="accountnumber">
            <label>Account #</label>
            <input readonly type="text" name="accountnumber" value="<?php echo $form['accountnumber']; ?>" <?php if($validated[1] == 'error') { echo 'class="error"'; } ?> />
        </li>


        <li id="companyname">
            <label>Company Name</label>
            <input type="text" name="companyname" value="<?php echo $form['companyname']; ?>" <?php if($validated[2] == 'error') { echo 'class="error"'; } ?> />
        </li>



        <li id="address">
            <label>Address</label>
            <input type="text" name="address" value="<?php echo $form['address']; ?>" />
            <input type="text" name="address2" value="<?php echo $form['address2']; ?>" />
        </li>




        <li id="csz">
            <label>City, State, Zip</label>
            <input id="city" type="text" name="city" value="<?php echo $form['city']; ?>" <?php if($validated[3] == 'error') { echo 'class="error"'; } ?> />

            <input id="state" type="text" name="state" maxlength="2" value="<?php echo $form['state']; ?>" <?php if($validated[4] == 'error') { echo 'class="error"'; } ?> />

            <input id="zip" type="text" name="zip" maxlength="5" value="<?php echo $form['zip']; ?>" />
        </li>


    </ul>



    <ul id="block2">
        <li id="products">
            <label>Products</label>
            <ul>
           <?php 

           //get all products from database
            $getproducts = mysql_query("SELECT id, name, url FROM products ORDER BY weight ASC");

            while ($rowproducts = mysql_fetch_array($getproducts)) {

                $product_id = $rowproducts['id'];
                $product_name = $rowproducts['name'];
                $product_url = $rowproducts['url'];

                $getuserhasproduct = mysql_query("SELECT DISTINCT product_id FROM products_accounts WHERE account_number = '$form[accountnumber]' AND product_id = '$product_id'");
                $user_has_product = mysql_num_rows($getuserhasproduct);

                if($user_has_product){
                    $hasproduct = true;
                }



            //list all products 
            ?>
                <li>
                    <label><?php echo $product_name; ?></label>
                    <input type="checkbox" name="<?php echo $product_id; ?>" value="TRUE" <?php if($user_has_product) { echo 'checked'; } ?> />
                </li>
            <?php



            //end while
            }
            ?>



            </ul>
        </li>


        <li id="demographics">
            <ul>
                <li id="beds">
                    <label>Beds</label>
                    <input type="text" name="beds" value="<?php echo $form['beds']; ?>" />
                </li>

            </ul>
        </li>


    </ul>


    <input type="submit" name="submit" value="Update" />


</form>





<?php
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Validate Function                          ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

function validate() {
    //get variables
    global $form;

    $v = true;

    //validate account number

    if(!$form['accountnumber']) {
        $v = false;
        $v1 = 'error';
    }

    if(!$newaccount) {
        $v5 = 'error';
    }

    //validate company name
    if(!$form['companyname']) {
        $v = false;
        $v2 = 'error';
    }

    //validate city
    if(!$form['city']) {
        $v = false;
        $v3 = 'error';
    }

    //validate state
    if(!$form['state']) {
        $v = false;
        $v4 = 'error';
    }

    $validated = array($v,$v1,$v2,$v3,$v4,$v5);
    return $validated;

}








////////////////////////////////////////////////////
////////////////////////////////////////////////////
////                                            ////
//// Process Function                           ////
////                                            ////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

function process() {
    //get variables
    global $form;
    global $_POST;

    //set variables for clean entry into database
    $an = mysql_real_escape_string($form['accountnumber']);
    $n = mysql_real_escape_string($form['companyname']);
    $a = mysql_real_escape_string($form['address']);
    $a2 = mysql_real_escape_string($form['address2']);
    $c = mysql_real_escape_string($form['city']);
    $s = mysql_real_escape_string($form['state']);
    $z = mysql_real_escape_string($form['zip']);
    $b = mysql_real_escape_string($form['beds']);




    //get all products from database
            $getproducts = mysql_query("SELECT id, name, url FROM products ORDER BY weight ASC");

            while ($rowproducts = mysql_fetch_array($getproducts)) {

                $product_id = $rowproducts['id'];
                $product_name = $rowproducts['name'];
                $product_url = $rowproducts['url'];

                $getuserhasproduct = mysql_query("SELECT DISTINCT product_id FROM products_accounts WHERE account_number = '$form[accountnumber]' AND product_id = '$product_id'");
                $user_has_product = mysql_num_rows($getuserhasproduct);

                //if the user has the product, let's delete it if we need to delete it, otherwise leave it alone.
                if($user_has_product){

                    if($_POST[$product_id] == false) {
                        mysql_query("DELETE FROM products_accounts WHERE account_number = '$form[accountnumber]' AND product_id = '$product_id'");
                    }

                //if the user doesn't have the product, let's add it if we need to add it, otherwise leave it alone.
                } else {

                    if($_POST[$product_id] == true) {
                        mysql_query("INSERT INTO products_accounts (account_number, product_id) VALUES ('$form[accountnumber]', '$product_id')");
                    }
                }


            }




    $result = mysql_query("UPDATE company_profiles SET name = '$n', address = '$a', address2 = '$a2', city = '$c', state = '$s', zip = '$z', beds = '$b' WHERE account_num = '$an'");

    if(!$result) {
        $processed = false;
        die('Could not connect: ' . mysql_error());
    } else {
        $processed = true;
    }


    return $processed;

}



?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

记忆之渊 2025-01-08 07:37:32

您可以在 Drupal 中使用任何您想要的 PHP 函数。问题是您在 include() 文件中定义了一个函数,该文件被包含多次。错误消息非常具体:“Cannot redeclare validate()`” - 一旦声明了函数,就无法重新声明它。

将函数放入一个单独的库文件中,该文件通过 include_once()require_once() 加载,这样它只加载一次。

You can use any PHP function you want within Drupal. The problem is that you're defining a function in an include()'d file, which is being included multiple times. The error message is very specific: "Cannot redeclare validate()`" - once a function is declared, you can't redeclare it.

Put the function into a separate library file which gets loaded via include_once() or require_once(), so that it's only loaded ONE time.

十年不长 2025-01-08 07:37:32

Drupal 可能有自己的 validate() 函数。 drupal 中的标准做法是在函数名称前添加模块名称,如下所示:editcompany_validate()。尝试一下,看看是否可以消除冲突。您应该能够进行简单的搜索和替换。

Drupal may have its own validate() function. Standard practice in drupal is to prepend your function names with the name of your module, like so: editcompany_validate(). Try that and see if it clears up the conflict. You should be able to do a simple search and replace.

蹲墙角沉默 2025-01-08 07:37:32

您可以为所有函数添加独特的前缀,以确保与 Drupal 的内部结构不发生冲突,或者如果您使用的是 5.3 及更高版本,则可以使用 PHP 命名空间。

当您调用全局函数时,使用命名空间可能需要对代码进行一些更改。然而,这是有据可查的。
https://www.php.net/manual/en/language。命名空间.fallback.php

You can prefix all of your functions with something unique to make sure there are no clashes with Drupal's internals, or you can use PHP namespaces if you are using 5.3 and above.

Using namespaces might require some changes in the code when you call global functions. However, this is well documented.
https://www.php.net/manual/en/language.namespaces.fallback.php

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文