Site icon T4Tutorials.com

Prime Number Program in PHP with Form and Database

Prime Number Program in PHP with Form and Database.

In this tutorial, we will learn about the following;

  1. Prime Number Program in PHP
  2. Prime Number Program in PHP with Form 
  3. Prime Number Program in PHP with  Database

Prime Number Program in PHP.

In this example, programmer stores the values in the variables. However, if you interested to see the program about taking values in the form, please see example 2.

<html>

<body>
<center>
<h2>Program 1</h2>
<p>Prime number program in PHP </p>

<?php

$num=29;
$LeastPrime=2;
 if($num<2)
  {
  echo"$num is less than 2 Smallest prime number is 2";
  }
  for($LeastPrime=2;$LeastPrime<$num;$LeastPrime++)
  {
  if($num%$LeastPrime==0)
  {
    echo"$num is not a prime number";
  break;
  }
  }
 if($num==$LeastPrime)
 {
 echo"$num is a Prime number";
 }
?>
</center>
</body>
</html>

Prime Number Program in PHP with Form.

In this example, we will take the inputs from the user and store them in variables.

<html>
<body>
<center>
<h2>Program 2</h2>
<p> Prime number program in PHP (Using Form) </p>
<h2>
<form method="post">
<label>Enter any number</label><br />
<input type="text" name="number"  /><br />
<input type="submit" name="submit" />
<br /><br />
</form></h2>
<?php
if(isset($_POST['submit'])){
$num=$_POST['number'];}
$Counter=2;
 if($num<2)
  {
  echo"$num is less than 2 and Smallest prime number is 2";
  }
  for($Counter=2;$Counter<$num;$Counter++)
  {
  if($num%$Counter==0)
  {
  echo"$num is not a prime number";
  break;
  }
  }
 if($num==$Counter)
 {
 echo"$num is a Prime number";
 }

?>
</center>
</body>
</html>

Prime Number Program in PHP with  Database.

In this example, we will take the inputs from the user and temporarily store them in variables and then finally stores them permanently in the database.

<html>
<body>
<center>
<h2>Program 3</h2>
<p> Prime number program in PHP (Using Form and SQL) </p>
<h2>
<form method="post">
<label>Enter any number</label><br />
<input type="text" name="number"  /><br />
<input type="submit" name="submit" />
<br /><br />
</form></h2>
<?php
if(isset($_POST['submit'])){
$num=$_POST['number'];
$Counter=2;
 if($num<2)
  {
  $result="$num is less than 2 and Smallest prime number is 2";
  echo"$num is less than 2 and Smallest prime number is 2";
  }
  for($Counter=2;$Counter<$num;$Counter++)
  {
  if($num%$Counter==0)
  {
  echo"$num is not a prime number";
  $result="$num is not a prime number";
  break;
  }
  }
 if($num==$Counter)
 {
 echo"$num is a Prime number";
 $result="$num is a Prime number";
 }
 
$con=mysqli_connect("localhost","root","","test2");
$sql=mysqli_query($con,"INSERT INTO prime (Number,Result) VALUES ('$num','$result')");
}
?>
</center>
</body>
</html>

Database of Prime Number Program.

Figure: prime number program in PHP with database and form.

 

Exit mobile version