Solved

Counter with php

Posted on 2013-01-10
26
322 Views
Last Modified: 2013-01-12
Hello Experts!

I have this counter for my web page:

flip
This counter will be rendering the a total number of entries in the database, I am using SUM(php). Anyways, how would I put an image in every number beeing those numbers loaded from the database/php??

I saw some counters on the web but all numbers have span's around it and I am not sure how to sinc with php.

I don't need any animation, this will be static. Just load the numbers and add to each number a background image like in the image above.

my test code:

<div id="soma">
	<h3>Total Annual Income</h3>

<?php


$query = "SELECT id, SUM(id) FROM users"; 
	 
$resultu = mysql_query($query);

while($row = mysql_fetch_array($resultu)){
	echo $row['SUM(id)'];
}
?>




</div>

Open in new window


Thanks a lot
0
Comment
Question by:joao_c
  • 13
  • 5
  • 4
  • +1
26 Comments
 
LVL 7

Expert Comment

by:rgranlund
ID: 38764809
while($row = mysql_fetch_array($resultu)){
      if ( $row['SUM(id)']== "1") {
echo '<img src="img/1.jpg"/>';
}

However, I think there is way to simplfy by creating a background for the number and then just style the font that the number is using instead of creating a bunch of images.
0
 
LVL 3

Expert Comment

by:Pedro Chagas
ID: 38764821
Hi, That change occurs just when open the page or you want change the counter more then once in every session?

The best regards, JC
0
 

Author Comment

by:joao_c
ID: 38764837
I just need to update it on page refresh.

It would be nice to a have a simple css class with background imagem and font styling, and apply it to all numbers loaded from php. (Not sure if it is possible or the best solution).

Thanks
0
 
LVL 3

Expert Comment

by:Pedro Chagas
ID: 38764926
Boa noite João,
Não sei se já experimentas-te a solução do @rgranlund, á primeira vista está bem escrito e o resultado final é o numero que mais tarde será visível na página.
Há aqui uma coisa que não entendo, para que é que é preciso fazer um ciclo no script, pergunto, o resultado que está na bd não é já o resultado final a apresentar?

Quanto á apresentação do numero na pagina estilizado, deves usar CSS, e se me disseres qual a dificuldade que tiveres em CSS, eu ajudo-te.

Cumprimentos,
JC
0
 

Author Comment

by:joao_c
ID: 38764967
Olá João.

Eu tenho um formulário no site que vai acumular empresas na base de dados, e somar os rendimentos de todas as empresas que subscreverem.

Aquele bloco de php vai somar os rendimentos das empresas e apresentar na página. Eu copiei aquilo de um livro qualquer de php e resultou. Provavelmente o loop não é preciso. Php não é de todo o meu forte. Mas como é um projeto simples acabei por me safar. Falta agora estilizar os números.

Vou tentar o sugerido.

Cheers.
0
 
LVL 3

Expert Comment

by:Pedro Chagas
ID: 38764983
Hi  @rgranlund, what I said in my last post in Portuguese was, that your script is a good solution for the php part. They also need to use CSS to define the style of the numbers of the counter.

~JC
0
 
LVL 3

Expert Comment

by:Pedro Chagas
ID: 38765002
Se precisares de ajuda em CSS diz.
Já vi que és um membro recente do EE. Já cá estou á cerca de 3 anos, sempre como membro premium (embora ás vezes ajude também os outros), diga-se de passagem que é um dos melhores dinheiros entregues na Internet.

Um abraço,
João Chagas
0
 

Author Comment

by:joao_c
ID: 38765224
Back in English :)

Joao, how would I add an image to every single number? Do I have to wrap every number in a span tag?

Thanks
0
 
LVL 7

Expert Comment

by:rgranlund
ID: 38765242
Is this what you need/mean?

<style>
#counter {
height:100px;
width:300px;
background-image:url(../img/COUNTER-BACKGROUND.jpg);
background-repeat:no-repeat;
}

.counter_number {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
color:#ffffff;
}
</sty/e>

while($row = mysql_fetch_array($resultu)){
	echo '<div id="counter"><span class="counter_number">' . $row['SUM(id)'] . '</span></div>;
}
?>

Open in new window

0
 

Author Comment

by:joao_c
ID: 38765265
Thanks for the reply rgranlund.

Probably it is what I need. I will have to run a test to see if it's ok and then follow up with a comment or accept as a solution. Just can't do it right now.

Be right back.
0
 

Author Comment

by:joao_c
ID: 38765487
The code only creates an image, and not several images for all the numbers. I might end up having a number like "1.000.000.000" and I need a background for every single number.

Thanks
0
 

Author Comment

by:joao_c
ID: 38765509
Ok, please have a look at this examle:

http://jsfiddle.net/RQrP4/3/

how to integrate the number generated from php in those divs? Like "php give to every single number a class with that background"!

Thanks
0
 

Author Comment

by:joao_c
ID: 38765556
Even simple based on my code:

http://jsfiddle.net/Srb9b/1/

What I need is that every number in the spans to be replaced with the numbers from the php/database.

Thanks
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 33

Expert Comment

by:Slick812
ID: 38768491
greetings  joao_c , , what you want to do is not a very simple thing to first set up, You seem to want Custom "Look" as in your flip-ex.png. . . . I would use a set of 10 images named numerically as   num0.png   num1.png   num2.png for each number 0-9 and one for the separator .  called  sep.png  then try something like -

while($row = mysql_fetch_array($resultu)){
	$sum = ''.$row['SUM(id)'];// get number as String with ''.
}

$nums = str_split($sum); // get each string character in an array $nums

// this seems easiest in a Table for short code
// but you can use DIV - SPAN if that suits you, but there may be more code
echo '<table cellpadding="4"><tr style="background:#aaa;">';
$sep= 0;
foreach ($nums as $value) {
if ((($sep % 3) = 0) & ($sep != 0)) echo '<td><img src="sep.png" /></td>';
echo '<td><img src="num'.$value.'.png" /></td>';
++$sep;
}
echo '</tr></table>';

Open in new window


this is untested code, but should give you an idea on a way to do this, you will likely need to make or get your Custom Look number images, although there is much that STYLE sets can do for a custom look, it can not deliver the variety and specific "Look" in each browser that an image can.
although if you just want a TEXT version in the foreach loop you might use something like
echo '<span class="num">'.$value.'</span>';


If you need more info, ask questions.
0
 

Author Comment

by:joao_c
ID: 38768539
Thank you so much for the reply, but having that ammount of images will be too much. :s

Have u seen this? http://jsfiddle.net/Srb9b/1/

Just need that each number from the php goes to their respective span. And then I can style the span class with a black bg like in the example. Is not possible?

Thanks again.
0
 
LVL 7

Expert Comment

by:rgranlund
ID: 38768641
Sure, this is possible.  But it will need an additional operation to determine how many digits are returned and then break it apart.  I'm looking into the php for you now.
0
 

Author Comment

by:joao_c
ID: 38768666
Thanks a lot guys.
0
 
LVL 7

Expert Comment

by:rgranlund
ID: 38768730
@Slick Can you re-write that so it prints out each number in its own div span?

Like the following? This is closer to what he is asking for I think, but I'm not sure I have written it correctly.

<style>
#counter {
height:100px;
width:300px;
background-image:url(../img/COUNTER-BACKGROUND.jpg);
background-repeat:no-repeat;
}

.counter_number {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
color:#ffffff;
}
</sty/e>

<?php
$query = "SELECT id, SUM(id) FROM users"; 	 
$resultu = mysql_query($query);
echo '<div id="counter">';
while($row = mysql_fetch_array($resultu)){
	$sum = ''.$row['SUM(id)'];// get number as String with ''.
}
$nums = str_split($sum); 
$sep= 0;
foreach ($nums as $value) {
echo '<div class="counter_number">'.$value.'</div>';
++$sep;
}
echo '</div>';
?>

Open in new window

0
 
LVL 33

Expert Comment

by:Slick812
ID: 38769227
@rgranlund, , I looked at the <style> for your "counter_number" and can NOT see how that could work in a DIV block container , , which do NOT line up side by side, but stack one on top of the other, , and you make NO provision for for the separator  .  needed for the display of the  flip-ex.png  example.
I also looked at the page at    http://jsfiddle.net/RQrP4/3/     for the jsFiddle and the DIV structures and CSS style for the divs, it's much to complicated for me to spend my time figuring it out, right now, and I do not see a need for complicated to do this sort of thing. If you want to use jsFiddle (javascript I believe, and has little to do with PHP) then I can not follow that code path. sorry. You failed to notice that the three numbers displayed in jsFiddle all had a separate complicated DIV structure, instead of the single <div class="counter_number"> you use.
I have done arrangements with horizontal div rows, not easy, and it's easier for me to use Tables, DIVs do not naturally line up in horizontal positions, you'll have to assign width and heights to the counter_number Divs, and use some sort of float: left; or right,  but the blocks will slide under if the container width if off. Tables will maintain the arrangement no matter what.

The code below as something for the period separator to be added, but using your STYLE conditions, it won't work.
$sep= 0;
foreach ($nums as $value) {
if ((($sep % 3) = 0) & ($sep != 0)) echo '<div class="grey"> . </div>';// write a period with a grey background
echo '<div class="counter_number">'.$value.'</div>';
++$sep;
}

I may have time tomorrow to try something, , , rgranlund I hope you can try something and get the code for  joao_c  to use.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 38769328
OK,  I have done My version of this number display, it more or less matches most of the   flip-ex.png  display, but it can NOT do everything that one can think of for this kind of display, for instance if has a fixed width, I use a DIV here because it seems like some here like that kind of thing, BUT it does NOT expand and contract width with the size (length) of the number.

$sum = '8902587';
$nums = str_split($sum);
$co= count($nums)-1;
echo '<div style="width:190px; height:23px; color:#fff; font-size:21px; border:2px solid #ccc; background:#9ac; padding:4px; text-align:center;">';
$nums = array_reverse($nums);
for ($i = $co; $i > -1; --$i) {
	if (($i != $co)&(($i%3) == 2))echo '<span style="padding:2px 0px 2px 0px; border:2px solid #9ac;">.</span>';
	echo '<span style="background:#000; padding:2px 3px 2px 3px; border:2px solid #9ac;">',$nums[$i],'</span>';
	}
echo '</div><br />count= ';

Open in new window


you will have to experiment with the style your self to adjust the colors,  font size, or the font face or the height, or any thing tht you may need or want.
0
 

Author Comment

by:joao_c
ID: 38769916
This is great, just a need to know how to make that $sum variable beeing the result from a "SUM":

My code to calculate the total

$query = "SELECT id, SUM(id) FROM empresas"; 
	 
$resultu = mysql_query($query);

while($row = mysql_fetch_array($resultu)){
	echo $row['SUM(id)'];
}

Open in new window


How to I assign to "$sum = '8902587';" value the result from my code above?

Sorry for my ignorance, and thanks a lot. This is about to solve my problem. :)
0
 

Author Comment

by:joao_c
ID: 38769987
I was thinking that maybe jquery can solve this issue in a more easy way. Consider the following code:

$('ul.numeros').children(':nth-child(1)').html('8');
$('ul.numeros').children(':nth-child(1)').html('2');

So, I have the style already done and why dont I use jquery/javascript to grab the value returned from the php(SUM), let's say '256' and assign each value similar to the code above?

What do you guys think?
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 38770188
you ask - "make that $sum variable beeing the result from a "SUM":"

I have already given you that code method in comment ID: 38768491 , ,  in case you can not do basic PHP ,  ,here is that re copied here. -

$query = "SELECT id, SUM(id) FROM users"; 
	 
$resultu = mysql_query($query);

while($row = mysql_fetch_array($resultu)){
    $sum = ''.$row['SUM(id)'];
    }

$nums = str_split($sum);
// rest of code follows

Open in new window


you also ask - " maybe jquery can solve this issue in a more easy way."
if you want to use jquery (which is a Javascript package), go ahead and do whatever you like, but I do not see any Javascript advantage, All of this code processing (split up the number string to individual characters, add the . every 3 numbers) can be done server side in PHP.
I do not follow that using -
$('ul.numeros').children(':nth-child(1)').html('8');
would be more simple? you still need to do the actual number sting "37621" processing, you could write javascript code OR PHP code to do that, but either way someone has to do the coding.
0
 

Author Closing Comment

by:joao_c
ID: 38770364
Perfect solution. Thank you so much.

Thanks also for all the other people that helped in this post.

Cheers
0
 

Author Comment

by:joao_c
ID: 38770379
Not sure if I can still ask but one final thing:


The numbers rendered in the page should have 5 digits like "16.908";

The current number returned from the database is "81". I need to make all the other numbers "0" on the left. Like "0.081";

Is this possible? Like" php if there's no 5 digits render "0's" on the left;



Also I have other counter with 10 digits like: "0.056.545.246";

Need to apply the same pattern to add 0's on the left, the current number is "1027", so I should see "0.000.001.027";


Again, sorry if I am asking too much, if you have some time and it's easy to implement in the current code, let me know.

Thanks a lot
0
 
LVL 33

Expert Comment

by:Slick812
ID: 38771092
I can show you this, but you may learn very little by coping my code, please look up the php function  str_pad( ) and use it to place any characters on Left or right of any string to a certain length.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
In this tutorial viewers will learn how to style rounded corners for elements in CSS using the border-radius property Begin with a normal styled element such as a div: To style all four corners of the div to be the same degree of roundness, use the …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now