0
function givemeposts($user, $pos){
$sql = "select * from posts where user ='" . $user . "' and pos = '" . $pos . "' order by inde";    
...

givemeposts('public', 'home01'); // this works as usual

Now I nedd to call the above function, but without $pos param, i.e. whatever $pos value is.

Something like:

givemeposts('public', whatever);

Any way to do this?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 2
    You can make the argument optional, `function givemeposts($user, $pos = ''){` for example. – Qirel May 22 '17 at 13:24
  • 1
    Your code is vulnerable to sql injection – ollaw May 22 '17 at 13:25
  • check [this question](https://stackoverflow.com/questions/34868/how-do-you-create-optional-arguments-in-php) – rbock May 22 '17 at 13:26
  • @Ollaw, sql injection using SELECT statement !? Could you give me an example, pls. – qadenza May 22 '17 at 13:50
  • @Qirel, so, how can I call the function WHATEVER is in the `pos` column? The column is not empty! – qadenza May 22 '17 at 13:56
  • @bonaca It's always a bad practice put variables directly inside a query. I recommend you to use mysqli or PDO. http://php.net/manual/en/book.mysqli.php http://php.net/manual/en/book.pdo.php – ollaw May 22 '17 at 14:11

3 Answers3

1

You can use default parameter :

function givemepost( $user , $pos=NULL ){
    if($pos==NULL){
        //some code
    }lese{
         $sql = "select * from posts where user ='" . $user . "' and pos = '" . $pos . "' order by inde";    
    }
}

This way you can call the function with one paramter, and set what the function have to do, inside the if branch.

ollaw
  • 2,086
  • 1
  • 20
  • 33
1

In PHP you can set default values for arguments

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

If you do this, the default value for $pos will be '' (an empty string):

function givemeposts($user, $pos = ''){

Or you can something else than an empty string, whatever value you want:

function givemeposts($user, $pos = 'SomeValue'){

Then you can simply call your function like this:

givemeposts($user);
lloiacono
  • 4,714
  • 2
  • 30
  • 46
1

You can try this:

function givemeposts($user, $pos = '')
{
    if(!empty($pos)) {
        $pos = "AND pos = '" . $pos . "'";
    }
    $sql = "SELECT * FROM posts WHERE user ='" . $user . "' $pos ORDER BY inde";

}

givemeposts('public'); 
Timur
  • 488
  • 4
  • 14