【问题标题】:disable php function with other function用其他功能禁用 php 功能
【发布时间】:2015-01-06 17:15:49
【问题描述】:

我想知道是否有办法在调用另一个函数时禁用现有的 php 函数(或部分)。

我的情况如下: 我有一个带有文本输入的 php 搜索功能。这工作正常。 (见下面的代码)

if(isset($_POST['search'])){
if(isset($_GET['go'])){
if(preg_match("/[A-Z | a-z]+/", $_POST['search'])){
$input=$_POST['search'];

//connects to database
//selects database table
//searches database
//assigns $results variable

//outputs results:
while($row=mysql_fetch_array($result)){
echo 'results...';

}}}} else {
//connects to database
//selects database table
//searches database:
$sql="SELECT * FROM table";
//outputs results (same as above)
}

所以这是我工作搜索功能的一个非常简短的形式。在这个搜索功能下方,我有一个按钮——当点击它时——应该输出一个特定字符串的搜索结果。这也有效。问题是当这个按钮被点击时,它显示上面函数的“else-part”,而我只希望它显示该特定字符串的结果,而不是其他“表项”... 现在遵循 search-for-one-specific-string 部分的代码:

function results_for_one_specific_string () {
//connects to database

//searches database:
$sql="SELECT * FROM table WHERE Name='string'";
//outputs results (same as above)
}

if (isset($_GET['button123'])) {
results_for_one_specific_string ()
}

只是为了让你知道,为了打电话给function results_for_one_specific_string (),我使用了这样的东西:

<a href="index.php?button123=true" title="">title</a>

现在我的问题是:有人知道我如何才能以某种方式“禁用”我的搜索功能的“其他部分”(第一个代码块)在调用 function results_for_one_specific_string () 时? (以便只打印此函数的结果,而不是第一个函数的“其他”方)

谢谢你们!

【问题讨论】:

  • 好的,伙计,我需要查看更多您回答的代码,这应该不难。但我需要更多地了解您的想法以及您在寻找什么。请提供完整的代码

标签: php


【解决方案1】:

这样的东西对你有用吗?

$hasBeenCalled = false; // Set a global var

function results_for_one_specific_string () {
    //connects to database
    //searches database
    //outputs results
}

if (isset($_GET['button123'])) {
    $hasBeenCalled = true; // Update global var here
    results_for_one_specific_string ()
}

...

if(isset($_POST['search'])){
    //connects to database
    //searches database
    //outputs results
} else if($hasBeenCalled==false){ // Check for global var here
    //outputs all table items (not only the search results, everything!)
}

【讨论】:

  • 你的回答对我来说完全有意义,但不幸的是,当我调用“results_for_one_specific_string”函数时,它仍然输出搜索函数的 else 部分......
  • 我认为这完全取决于函数何时被调用,在if(isset($_POST['search'])){ 代码运行之前还是之后?
  • 非常感谢!我只需要在您的答案中的第二个 if 语句中添加另一个“$hasBeenCalled = true;”!现在它对我有用!
【解决方案2】:

对我来说,您似乎使用相同的代码来搜索自定义字符串以及特定字符串。如果这是真的,那么为这两种情况创建一个函数会更容易和更透明:

function results_for_any_string ($search='') {
if(strlen($search>0)){
//connects to database
//searches database
//outputs results
}
else {
//outputs all table items (not only the search results, everything!)
}
}

在主脚本中选择要用作参数的内容。

if(isset($_POST['search'])) $parameter = $_POST['search'];
else if (isset($_GET['button123']))  $parameter = $_GET['button123'];
else $parameter='';
results_for_any_string ($parameter);
}

此外,如果一个表单中没有按钮,您也可以通过相同的表单和 POST 提交特定值。不混合发布和获取。参见例如this post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2017-03-13
    • 2014-04-10
    • 2018-12-10
    相关资源
    最近更新 更多