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

mysql_query(insert)
mysql_query not working in php 7
mysql function in php with example
mysql functions in php 7
mysql functions in php pdf
php mysql fetch
php mysql query result
mysqli_query not working

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':

http://i.imgur.com/0XWBqtR.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>';
}

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'];
}

PHP: MySQL Functions - Manual, The mysql_fetch_[row|object|array] functions return data as type string. Owing to the very flexible nature of php variables, this is normally not relevent, but if from a database, then try to compare with bitwise operators, you'll run into trouble, inside queries, but I hope it helps others who are in posession of such dumps. 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 s

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.

Can I include a function inside of another function?, How do you call a function within a function in PHP? If you need to execute sevaral SQL commands in a row (usually called batcg SQL) using PHP you canot use mysql_query() since it can execute single command only. Here is simple but effective function that can run batch SQL commands.

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);

How to call a function or method inside its own class in php?, What is the correct way to create a function in PHP? PHP Built-in Functions. A function is a self-contained block of code that performs a specific task. PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.

How to Define and Call a Function in PHP, How do you retrieve data from database in PHP using MySQLi? MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH.

MySQLi - Select Query, . This function returns row as an associative array, a numeric array, or both. Now, inside /inc/class/DAL.php, we will make a function that we will use to connect to our database. The connection, as well as all forthcoming queries, will live inside a class named DAL . Wrapping all database involvement inside a single class allows us to manipulate our queries later without needing to touch business or presentation layer

mysql_query - Manual, Data inside the query should be properly escaped. The following query is syntactically invalid, so mysql_query() fails and returns FALSE . this db class/​function will accept an array of arrays of querys, it will auto check every line for put a large amount of text or data (blob) into a mysql table you might run into problems. Thanks in advance for any help. I have a php file that displays a form with several pull downs populated from data in a database. For one of these pull downs, when the selection is changed I need to display text based on the selection (different column in db) and add a text field to the form.

Comments
  • eval(), but what you want is really bad, instead write a PHP mapping logic for this
  • don't put php in your db, its almost always a bad idea
  • So you want to run star5 how frequently? Also please show what star5 looks like.
  • I'd go for solution like this switch($row['sitename']) { case 1: star5(); break; case 2: someOtherFunction(); break; default: break; }
  • the 5star() function is only an echo statement that echos out 5 small lines of HTML that create 5 stars.
  • This will work with some more crafting, as eval might need a closing the current php tag, in order to not result in <?php <?php some code, but the main problem is that this does not care if the row contains star5() or not and will turn every string in arbitrary PHP code. As well as eval() is never the answer of a certain issue. If it is, then most probably the issue is wrong.
  • PLEASE DONT, think of the children.
  • Never EVER use eval() combined with user submitted data unless you're 100% sure that data is secured properly. And even then there are better ways to do it.