enrico-dev
enrico-dev

Reputation: 155

PHP - Call a function from a link\button

I know that PHP is only server-side and it's impossible to call directly a PHP-FUNCTION from a link.

But I can't use JavaScript \ jQuery \ Ajax

This is my code in main.php

function refreshgt2(){
    for($l=1; $l!=$max_cicle; ++$l ) {
        $data->query("INSERT IGNORE INTO `table` (`name1`,`name1`,`anothername`,`dog`) VALUES ('ME','".$img[$l]."','".$l."','".$hello[$l]."')");        
    }       
}

And the html,

<a href="#" >Do something</a>

I've just tried with this need a button that calls a php function but didn't work for me.

Someone can help me?

I need something that load the function only when I will press the link\button\image

Upvotes: 0

Views: 7065

Answers (5)

Jacky Cheng
Jacky Cheng

Reputation: 1556

this should work. it gives a button, support multiple function call and is pure php + html

<form action="<?php $_PHP_SELF ?>" method="post">
<input type="hidden" name="function" value="refreshgt2">
<input type="submit">
</form>

<?php 
if($_POST!=null && array_key_exists('function', $_POST)){
    if(strcasecmp($_POST['function'],'refreshgt2')==0){
        for($l=1; $l!=$max_cicle; ++$l )
        {
            $data->query("INSERT IGNORE INTO `table` (`name1`,`name1`,`anothername`,`dog`) VALUES ('ME','".$img[$l]."','".$l."','".$hello[$l]."')");        
        }
    }else if(strcasecmp($_POST['function'],'some_other_function')==0){
        //do things
    }
}
?>

Upvotes: 2

johnnynotsolucky
johnnynotsolucky

Reputation: 540

Use querystrings, set the href in your html to point to your page, and add a querystring parameter so that your php can decide which function to execute:

HTML

<a href='main.php?fn=some_function'>Do something<a/>

PHP

switch($_GET['fn']) {
case 'some_function':
    //call your function 
    break;
default:
    //Handle this
}

Otherwise, redirect to another php script like the other answers mentioned.

Upvotes: 0

acme
acme

Reputation: 14856

If you can't use javascript/ajax (why not? we are in 2013), you can't refresh part of the page on the fly. Your only chance is to call a page like

<a href="my-script.php">Do something</a>

and my-script.php then renders the page again after doing some stuff.

Upvotes: 0

DGS
DGS

Reputation: 6025

If you dont mind a redirect

<a href="your_php_script.php" >Do something</a>

you_php_script.php

<?php

refreshgt2();

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46910

But i cant's use a javascript\jquery\ajax

Then the answer is No, you can not. Only option is to link your button to a new page which will generate the PHP output. PHP itself does not know anything about what you do at client side and whether you have clicked a link, PHP functions cannot execute at that time since PHP has already done its job and gone.

Upvotes: 0

Related Questions