Home > Blockchain >  Fetching PHP code from table field in database
Fetching PHP code from table field in database

Time:09-23

I have a table notifications where I have a field notification which has value:

<?php echo '.$user['name'][0].' ?>, you are <?php echo popularity(); ?>% popular today.

The output is: , you are % popular today.

It is ignoring the PHP here. I don't understand why.

Expected output is Shubham, you are 35% popular today.

Under network in inspect element the response tab with raw data shows this:

<div class="notiText">
  <?php echo $user['name'][0]; ?> you are <?php echo popularity(); ?>% popular today.
</div>

What's the issue here? Why does the script does not load PHP tags from the database?

EDIT

I have tried using eval() from here Reading php code from database. However, I have to do that into the database and not in code. The new output has this eval(), you are eval()% popular today.. Still not reading.

Note: I cannot use eval() into the coding. This has to be dynamic and from database. Therefore, anyone who is thinking of suggesting eval() I need an alternative or a workaround to the situation with eval() and database.

UPDATE

Here is the sample code:

processes/notifications.php

$stmt = $pdo->prepare("SELECT notification FROM notifications");
$stmt-> execute();

$html = "<div class='notifications'>";
while($f = $stmt->fetch()){
  $html .= '<a href="'.$link.'">'.$f['notification'].'</a>';
}
$html .= "</div>";
echo $html;

Jquery

$(".notificationsBell").on("click", function(e){
  $.ajax({
    type: "POST",
    url: "processes/notifications.php",
    data: "all",
    success: function(data){
      $(".loadNotifications").html(data);
    }
  });
});

HTML

<div class="loadNotifications"></div>

UPDATE 2

Okay so the following code is giving me the proper output.

$str = ''.$user['name'][0].', you are '.popularity().'% popular today.';

eval("\$str = \"$str\";");
echo $str;

Output: Shubham Jha, you are 100% popular today.

Now, how do I insert that string (the value of $str) into the database? In the table field what should be the format so that it gets recognized and echoed correctly. I tried this but doesn't work.

'.$user['name'][0].', you are '.popularity().'% popular today. 

Returns this error:

Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in E:\xampp\htdocs\newchat\processes\notifications.php(65) : eval()'d code on line 1

CodePudding user response:

Try this:

while($f = $stmt->fetch()){
  // STORE IN SIMPLE VARIABLES 
  $name = $user['name'][0];
  $popularity = popularity();

  $notiText = $f['notification'];
  eval("\$notiText = \"$notiText\";");

  $html .= '<a href="'.$link.'">'.$notiText.'</a>';
}

In the database use these simple variable names and avoid using quotes.

$name, you are $popularity% popular today.

  • Related