PHP MySQL ROUND() Function
Last Updated :
29 Aug, 2022
In this article, we are going to see how MySQL ROUND() function works in PHP. The MySQL ROUND() function is used to round a number to specified decimal places. If no specified decimal places is provided for round-off then it rounds off the number to the nearest integer.
Syntax :
ROUND(X, D)
SELECT ROUND(column1), ... ROUND(column n)
from TABLE;
Here, we are taking the student database to perform round() operation.
Requirements:
PHP is a server-side scripting language that communicates with MySQL to manage the databases. MySQL is an open-source relational database management system (RDBMS). MySQL is developed, distributed, and supported by Oracle Corporation.
Database Table Screenshot:
MySQL Query to Round-off parent_salary:
SELECT parent_salary, ROUND(parent_salary) FROM student;
Result:
Parent salary : 50000 — rounded to : 50000 Parent salary : 25000.8 — rounded to : 25001 Parent salary : 10001 — rounded to : 10001 Parent salary : 50000 — rounded to : 50000 Parent salary : 50000 — rounded to : 50000 Parent salary : 89000.1 — rounded to : 89000
MySQL Query to Round-off Student Marks:
SELECT name, ROUND(percentage) FROM student;
Result:
Student name : ojaswi — percentage : 79 Student name : sravan kumar — percentage : 98 Student name : bobby — percentage : 80 Student name : ojaswi — percentage : 79 Student name : rohith — percentage : 89 Student name : gnanesh — percentage : 69
Approach:
- Start the XAMPP server.
- Open phpMyAdmin database manager and create a database named test.
- Create a table named student inside the test database.
- Insert the student’s records into the table. To insert the data into the table, we can use SQL query or can insert data directly into the table.
- Write PHP code to perform the MySQL round() function and get the round-off data.
Program:
PHP
<?php
$servername = "localhost" ;
$username = "root" ;
$password = "" ;
$dbname = "test" ;
$conn = new mysqli( $servername ,
$username , $password , $dbname );
echo "Parent Salary" ;
echo "<br><br>" ;
$sql = "SELECT parent_salary,
ROUND (parent_salary) FROM student";
$result = $conn ->query( $sql );
while ( $row = mysqli_fetch_array( $result )){
echo " Parent salary : " .
$row [ 'parent_salary' ] .
" => Round-off : " .
$row [ 'ROUND(parent_salary)' ]
. "<br>" ;
}
echo "<br>*****************************" ;
echo "<br>Students Percentage" ;
echo "<br><br>" ;
$sql = "SELECT name, ROUND(percentage) FROM student" ;
$result = $conn ->query( $sql );
while ( $row = mysqli_fetch_array( $result )){
echo " Student name : " . $row [ 'name' ] .
" => Percentage : "
. $row [ 'ROUND(percentage)' ] . "<br>" ;
}
$conn ->close();
?>
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...