【问题标题】:href links leading to php if statement指向 php if 语句的 href 链接
【发布时间】:2012-09-16 06:22:44
【问题描述】:

PHP/HTML 问题

我希望这不是一个愚蠢的问题,但我正在尝试将来自两个链接的数据处理为 if 语句。我可以使用两个表单轻松完成此操作,因为表单可以具有名称如下的提交按钮:

<form action="process.php" method="post"> Enter your name: <input type="text" name="name" size="20"><br /> 
<input type="submit" name="edit" value="Edit"> 
<input type="submit" name="delete" value="Delete">
</form>

process.php中的if语句可以是if edit do this else do this。

我想做的是同样的事情,但来自一个 href 链接。由于标签在 HTML5 中没有名称,我该如何设置 if 语句?

感谢您的帮助。

【问题讨论】:

  • 为什么不直接检查 process.php 中是否存在 $_GET 参数?
  • 只需将其作为查询字符串的一部分添加:a href="process.php?edit=Edit"。唯一的区别是您需要查看 $_GET 而不是 $_POST 以查看它是否已设置 - 尽管 $_REQUEST 将涵盖这两种可能性。
  • 所以目前我将链接设置为 process.php?id=$id。我会将其更改为 process.php?id=$id&action=edit?

标签: php if-statement href


【解决方案1】:

您可以添加自定义 $_GET 变量,然后评估它们。例如 example.com/form?action=editexample.com/form?action=delete 然后在 PHP 中:

$action = $_GET['action'];
if($action === 'edit') {
    this;
} else if ($action === 'delete') {
    that;
}

【讨论】:

    【解决方案2】:

    例如:

    <a href="process.php?action=edit">Edit</a>
    
    <?php
    
    $action = $_GET['action'];
    
    if($action == 'edit'){
    // edit.
    }else{
    // else another action.
    }
    

    【讨论】:

    • 谢谢。是否可以为具有不同内容的多个页面提供相同的链接来编辑/删除?例如:带有edit/delete 的profile.php 使用if 语句链接到process.php,然后带有edit/delete 的categories.php 使用if 语句链接到process.php。如何区分这两个页面,以便可以根据来自哪个页面运行不同的 SQL 查询?
    • 您可以添加另一个 GET 变量,例如。 process.php?site=profile&edit 和 process.php?site=categories&delete 然后询问 if($_GET["site"]=="profile"){}...
    【解决方案3】:

    不知道我是否完全理解。 怎么样做这样的事情:

    <a href="process.php?delete">Delete</a>
    <a href="process.php?edit">Edit</a>
    

    然后

    if(defined($_GET["delete"])){
    }
    else if(defined($_GET["edit"])){
    }
    

    【讨论】:

      【解决方案4】:

      除非您将表单方法显式设置为get,否则表单通常会将请求作为post 发送。您可以通过调用$_POST["edit"] 在 PHP 中访问这些数据。

      常规链接可以在 URL 字符串中传递变量,例如 http://example.com/process.php?edit=true。您可以通过调用$_GET["edit"] 来访问这些变量。

      如果您想对 $_POST 和 $_GET 数据使用相同的 process.php 文件,您可以让代码使用 $_REQUEST 超全局 (http://php.net/manual/en/reserved.variables.request.php) 组合来自 $_GET、$_POST 和$_COOKIES

      在这种情况下,您的 PHP 代码将显示为:

      if ($_REQUEST["edit"]) {
          /* Some code */
      }
      elseif ($_REQUEST["delete"]) {
          /* Some other code */
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 2010-12-30
        • 2015-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多