user3870816
user3870816

Reputation: 85

How can I call a PHP function from inside a MySQL database table so that the function runs normally?

This is a really tough question to ask. He is my issue/question.

Is it possible to put a PHP function inside a MySQL table/cell and have the function run normally when called via a PHP query. If so How can I do it?

Here is my query code:

$recent_query = "SELECT * FROM `recently-added` ORDER BY `created` DESC LIMIT 4";

if(!$recent_query_result = $con->query($recent_query)){
    die('There was an error running the query [' . $con->error . ']');

}

Here is my loop code that displays the results of the query:

while($row = $recent_query_result->fetch_assoc()) {
  echo  '<div class="col-md-3 col-sm-6 md-margin-bottom-40">
        <div class="easy-block-v2">
            <div class="easy-bg-v2 rgba-' . $row['color'] . '">New</div>
            <img class="img-bordered" alt="' . $row['image-alt'] . '" src="' . $row['image'] . '">       
            <h3><i class="fa fa-smile-o"></i> ' . $row['site-name'] . '</h3>
            <!-- Begin Recently Added Footer Description -->
        </div>  
    </div>';
}

In my database and inside the table 'recently-added' I have a column named 'site-name'. I iterate through the loop and display the results onto my page. In the site name cell I put my PHP function for each record. That function is:

<?php star5(); ?>

When I refresh the page and look at where the function should be called it's a blank space. Nothing there. When I go to look at the source code to see if there is an error it shows me the exact characters that I put into the cell. It places the text onto the page and the server does not run the script or interpret the function.

Here is an image of the table in the database. This is in regard to te column 'site-name':

https://i.sstatic.net/15LtV.jpg

Been trying to fix this for almost 4 hours now. As always thanks in advance!

EDIT: Here is the function it's self

function star5() {

echo '<li><i class="color-green fa fa-star"></i></li>
      <li><i class="color-green fa fa-star"></i></li>
      <li><i class="color-green fa fa-star"></i></li>
      <li><i class="color-green fa fa-star"></i></li>
      <li><i class="color-green fa fa-star"></i></li>';
}

Upvotes: 0

Views: 2383

Answers (3)

Den Nikitin
Den Nikitin

Reputation: 37

I have a solution to run functions inside MySQL row or any other PHP string.

e.g., user needs to put a slider that gets its images from a server directory but he doesn't want to copy all the links, make an HTML code, etc.

The first thing you need to do is to create your own syntax for a function. I chose it to be like this -> [functionName('arg1', 'arg2')].

Create a StringParser class which finds all the occurances of your custom function inside of the given string, takes args and runs a custom function from the CustomFunctions class. Then it substitudes the text of your function inside of the given string to a returned value:

protected function substitute($string, $start) {
    $callback = "StringFunctions::".$start;
    $offset = 0;
    $start = '['.$start.'(';
    $end   = ')]';

    do {

        $argsArr = [];
        $argsArrNormal = [];

        $pos = strpos($string, $start, $offset);
        if (!$pos) return $string;

        $args_pos = strlen($start) + $pos;
        $args_len = strpos($string, $end, $args_pos) - $args_pos;
        $args     = substr($string, $args_pos, $args_len);
        $argsArr  = preg_split("/'\s*,\s*'/", trim($args));

        foreach ($argsArr as $arg) {
            $argsArrNormal[] = trim($arg, "'");
        }

        $replaced_value = call_user_func_array($callback, $argsArrNormal);
        $string = str_replace($start.$args.$end, $replaced_value, $string);

        $offset++;

    } while($pos);

    return $string;

}

After that, create a StringFunctions class with your custom functions which inherits StringParser. Function filter runs StringParser to check all the custom functions occurancies:

public function filter($string) {
    $string = StringParser::substitute($string, "printHTML");
    $string = StringParser::substitute($string, "printText");
    $string = StringParser::substitute($string, "multiply");
    $string = StringParser::substitute($string, "getDate");
    $string = StringParser::substitute($string, "printRect");

    return $string;
}

protected function printHTML(...$tags) 
{
    $result = '';
    foreach($tags as $tag) {
        $result .= "<$tag>";
    }
    return $result;
}

protected function printText(...$text) 
{
    $result = '';
    foreach($text as $key => $value) {
        if ($key == 0) continue;
        $result .= "<$text[0]>$value</$text[0]>";
    }
    return $result;
}

protected function printRect($amount, $width, $height, $color) 
{
    $result = '';
    for($i = 0; $i < $amount; $i++) {
        $result .= "<div style='margin:5px;width:$width;height:$height;background-image:url(https://picsum.photos/$width/$height/?random);display:inline-block'></div>";
    }
    return $result;
}

protected function multiply($number, $times) 
{
    return $number * $times;
}

protected function getDate($args) 
{
    return date($args);
}

run a code:

$StringFunctions = new StringFunctions(); 

$string = "A string can do more than just being itself[printHTML('hr')] [printRect('3','380','380','#eee')][printHTML('hr','br')] 13 * 14.4 =[multiply('13','14.4')][printHTML('br','br','hr')] [printText('h1','Hello, pony!')] Today is [getDate('Y - m - d')]!Today is [getDate('Y - m - d')]!Today is [getDate('Y - m - d')]!Today is [getDate('Y - m - d')]!";

echo $StringFunctions->filter($string);

Upvotes: 0

Nafis Abdullah Khan
Nafis Abdullah Khan

Reputation: 2390

Try using php eval() function. For example:

eval("\$row['site-name'] = \"$row['site-name']\";");

Also, remove the php tags from the data. Try with only keeping the star5() function call.

Check this Link for more details on eval.

Upvotes: 1

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

Not the best way, but as in the current situation, it's the solution which is most close to the good practices for introducing flags in DB in order to have logic over it.

Imagine you want to control if a user is administrator or not. You can add a column is_admin with 1 or 0 values, then while fetching the results you can check if ($row['is_admin'] == 1) { // proccess the logic for administrator } else { // process logic for normal user }

This could apply here, as you want to execute backend logic on certain event, or just show the row contents, if the event is not present.

According to be it will be one more level better if you introduce new column for this, and check it in order to know if you should call star5() or not, but in the current context you can add a string, on which presentation you will trigger the function.

Let's say the string is CUSTOM FUNCTION. Then, if you want to execute star5() upon fetch pointer moves on this row, then you add CUSTOM FUNCTION string in this row. Otherwise you add the normal content (e.g. real sitename).

Afterwards, when you fetch the records, you perform a simple condition check:

if ($row['sitename'] == 'CUSTOM FUNCTION') {
    star5();
} else {
    echo $row['sitename'];
}

Upvotes: 2

Related Questions