Hey guys so I'm just wondering how it is possible to format numbers when display data from a MySQL table using PDO?
At the moment I am printing my data using the following code:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '<div>
'.$row["Price"].'
</div>
';
} ?>
I have tried implementing number_format into my PHP however I keep getting a parse error.
Any idea how I can implement it properly so that my numbers contain commas?
Thanks
while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '<div>
'.number_format($row['price'], 2, ',', '.').'
</div>
';
}
Should do the trick.
Maybe you tried without the last parameter of number format, the function takes one, two or four parameters.
Related
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 .= ''.$f['notification'].'';
}
$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
Try this:
while($f = $stmt->fetch()){
// STORE IN SIMPLE VARIABLES
$name = $user['name'][0];
$popularity = popularity();
$notiText = $f['notification'];
eval("\$notiText = \"$notiText\";");
$html .= ''.$notiText.'';
}
In the database use these simple variable names and avoid using quotes.
$name, you are $popularity% popular today.
I am writing an application that will look at a single record, obtain values from about 12 flags (0 or 1), look up those flags against a status table (in MySQL) and return a variable called $status_message which is in that table.
In this table I need to have hyperlinks (working fine) but also echo some variables, i.e.
You have no bids for {{$row->_item_name}}
or
View this item now by clicking here
Now I need item name and the other example to be translated into <?php echo $row->_item_name; ?>
I have tried a preg_replace with the following:
<?php
$find = array('/{{/', '/}}/');
$replace = array('<?php echo ', ' ?>');
echo preg_replace($find, $replace, $status_message);
?>
but this is not working.
Can anyone advise how I can get the desired result and 'echo' the variable in the MySQL field?
Had a brainwave. Much simpler,
instead of $row->_item_name I just put {{itemname}} in the string. I then use the following code:
<?php
$message_buyer = str_replace('{{itemname}}', $row->_item_name , $message_buyer);
echo $message_buyer;
?>
so no need to have <?php calls in the string at all.
HI just found a solution about add and sustract two columns here but I need to make the php code to format the numbers.
Here is the solution I got here:
<?php
while ($row= mysqli_fetch_assoc($result)) {
echo $row['money'] - $row['cost'];
}
?>
Its working fine for what I need but here is the thing. I use to run the follow php code to all money and numbers
<?php echo number_format($product['cost'],0, ",", "."); ?>
That way the numbers will display without decimals and like this 100.000
How can I make the code I found here to work with number format?
Something like this I tried but does not work
<?php
while ($row= mysqli_fetch_assoc($result)) {
echo number_format$row['money'] - number_format$row['cost'];
}
?>
It must substract and then show the result with formated numbers
you need to put it in ()
echo number_format($row['money'] - $row['cost'],0,',','.');
More than 2 :
echo number_format($row['money'] - $row['cost'] + $row['whatever'] * $row['whatever'],0,',','.');
I'm trying to encode special entities with a function, here what I'm trying to do:
its a ratable function, with ratables stars, i have two functions that displays a ratable message, one is displaying default results, and the second when i give it a new rate
function showStars($ratableKey) {
...
$textDesc = "<div id=\"rabidRating-$ratingId-description\" class=\"ratingText\">"
.$this->getStarMessage($rating)."</div>";
echo $textDesc
}
i am call the getStarMessage in two different ways
function getStarMessage($rating) {
$stars = $this->percentToStars($rating['rating']);
if ($rating[totalRatings] > 1) $s = "s";
$div_stars = "<div class=\"rate\">";
$result= "$stars/$this->stars ".$div_stars." ($rating[totalRatings] avis)</div>";
$result= html_entity_decode($result);
return $result;
}
In the defaut way (in showStars function ) it works fine (with or without the html_entity_decode)
but when I called the getStarMessage function in another function
function doVote($ratableId, $percent) {
...
$rating = $this->loadRating($id);
$return = $this->getStarMessage($rating);
echo $return; ==> the problem is here
}
in source code it displays
<div class="ratingText " id="rabidRating-9-description">2.8/5 <div class="rate"> (141 avis)</div></div>
and therefore, the output is this
2.8/5 <div class="rate"> (142 Stars)</div>
It's not displaying as html entities but as simple string.
Am I doing something wrong ?
Here some screenshot :
displaying default :
After rating (clik on stars)
You want that div.rate to be rendered as HTML? if so, then you shouldn't put the "<" etc entities -> that makes the exact opposite from what you want - it keeps the "less than" character in the string.
So, if I understood you well, your code has to be
<div class="ratingText " id="rabidRating-9-description">2.8/5 <div class="rate"> (141 avis)</div></div>
Good luck.
So I'm basically calling and returning an entire row from a mysql table using a while loop (which is working), but I'm trying to use the data that I call inside an html link, but I can't seem to get it to work.
Ideally, eventually it will just be a list of links with each person's individual name. I can return the list fine, but I can't seem to return the list with a link.
Here is my code that I feel should be working :(
<?php
require 'db/connect.php';
$result = $con->query('SELECT distinct name FROM mytable');
while($rows = $result->fetch_assoc())
{
echo ''$rows['name']'' , "</br>";
}
?>
Any help would be greatly appreciated!
Issue might be with your string concatenation. Try following code block
echo ''.$rows['name'].'';
echo ''. $rows['name']. '' , "</br>";
You just need to use . to concatenate strings together.
try this
echo ''.$rows['name'].'' , "</br>";
Should work just fine. Basically it's '.$row['name'].'
when concatenating strings with variables you have to use dot(.) like echo "string".$var; it will be invalid to write echo "string"$var; in your example you have ignored this point.