Jump to content

Help with a random image display code


kitten

Recommended Posts

Hello, I'm really new to PHP so I've been having some trouble figuring out how to set up a code on my site.

What I want it to do is pull a random name from my database and display it centered.  So far I have this code -

[pre]<?php

$link = mysql_connect("host", "user", "pass") or die (mysql_error ());

mysql_select_db ('cbnames', $link) or die (mysql_error ());

$sql = mysql_query ("SELECT `name` FROM `cb` ORDER BY RAND() LIMIT 0,1") or die (mysql_error ());

$res = mysql_fetch_assoc ($sql);

$randomname = $res['name'];

echo $randomname;

?>[/pre]

It works well at pulling up a random name but I still haven't figured out how to center it.

Next what I need is for it to display an image above the pulled name also centered.  The image I need is from a web link and I need the last part of the link to be the same as the random name pulled from the database.

 

Example ~

If the code I have pulled the random name Michael

The link to the image to be displayed would be ~

http://www.mysite.com:/names/namesdisplay.php?char=Michael

or

If the code pulled the name Jill the image link would need to be

http://www.mysite.com:/names/namesdisplay.php?char=Jill

Etc

 

I hope that makes sense, I'm really hopping its a simple code but since I'm not very good at PHP I've been struggling.

I hope someone can help me out, it will be greatly appreciated!

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/120450-help-with-a-random-image-display-code/
Share on other sites

<?php
$link = mysql_connect("host", "user", "pass") or die (mysql_error ());
mysql_select_db ('cbnames', $link) or die (mysql_error ());
$sql = mysql_query ("SELECT `name` FROM `cb` ORDER BY RAND() LIMIT 0,1") or die (mysql_error ());
$res = mysql_fetch_assoc ($sql);
$randomname = $res['name'];
echo '<div align="center"><img src="http://www.mysite.com:/names/namesdisplay.php?char='.$randomname.'" /><br />'.$randomname.'</div>';
?>

That's an html issue, not PHP.

 

Also, ORDER BY RAND() = bad. Don't do it.

 

Use PHP to generate a single random number based upon the number of entries you have.

 

RAND() forces MySQL to create a tmp_table every single query. Big database = huge slowdown.

 

Let PHP handle the random selection (It's faster!).

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.