1. Home
  2. Computing & Technology
  3. PHP / MySQL

PHP Magic 8-Ball

By , About.com Guide

A Magic 8-Ball PHP Script: The internet is full of fun and useless way's to waste your time. This tutorial shows you how to create one... an online magic 8-ball script sure to waste countless hours of your friend's time.
<html>
<head><title>Magic 8-Ball</title></head>
<body>
<h2>Magic 8-Ball</h2><p>

<?

//Only replies if there is a question
If ($question)
{

//Chooses a random number
$result = Rand (1,8);

//Reminds them of their question
Echo "Your question: $question <p>";

//Based on the random number, gives an answer

if ($result ==1)
{
Echo "The 8-ball says: Yes";
}

if ($result ==2)
{
Echo "The 8-ball says: No";
}

if ($result ==3)
{
Echo "The 8-ball says: Ask again later";
}

if ($result ==4)
{
Echo "The 8-ball says: Perhaps, perhaps, perhaps";
}

if ($result ==5)
{
Echo "The 8-ball says: The future is hazy";
}

if ($result ==6)
{
Echo "The 8-ball says: It is certain";
}

if ($result ==7)
{
Echo "The 8-ball says: Without a doubt";
}

if ($result ==8)
{
Echo "The 8-ball says: There is no chance";
}
}
?>

<form action = "<?php echo $_SERVER[’PHP_SELF’]; ?>" method = "post">
<p>
Question:<input type="text" name="question" />
<input type = "submit" name = "Ask"/>
</form>
</body>
</html>
This is basically how this script works:

1.) Regardless, it gives the user a form to enter their questions, which directs back to itself to process using $_SERVER[’PHP_SELF’]

2.) If a question exists, it choose a random number between 1 and 8.

3.) It echos their question

4.) Using the random number as a guide, it uses a conditional statement to give the corresponding 8-ball reply.
Explore PHP / MySQL
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Step By Steps
  5. Magic 8-ball PHP - PHP 8 Ball Script - PHP Random Eight Ball

©2009 About.com, a part of The New York Times Company.

All rights reserved.