PHP – My SQL : abs() – numeric function
Last Updated :
25 Mar, 2021
Problem Statement :
In this article, we are going to perform database operation with abs() operation using php.
So we are considering temperature database .
Introduction :
PHP stands for hyper text preprocessor, it also communicates with mysql database through xampp server.
MySQL is an query language that is used to manage the databases.
abs()
abs() is used to return the positive value in a table.
syntax :
abs(data);
Example :
abs(-12)=12
abs(23) = 23
Consider the table:
Convert the temperature column to positive.
Query :
SELECT city,ABS(temperature) FROM temperature;
Result :
city id : 1 — temperature : 15
city id : 2 — temperature : 455
city id : 3 — temperature : 55
Steps
- Create a database named database and create table named temperature.
- Write php code to insert records into the table.
temp.php
PHP
<?php
$servername = "localhost" ;
$username = "root" ;
$password = "" ;
$dbname = "database" ;
$conn = new mysqli( $servername , $username , $password , $dbname );
if ( $conn ->connect_error) {
die ( "Connection failed: " . $conn ->connect_error);
}
$sql = "INSERT INTO temperature VALUES (1,-15);" ;
$sql .= "INSERT INTO temperature VALUES (2,-455);" ;
$sql .= "INSERT INTO temperature VALUES (3,55);" ;
if ( $conn ->multi_query( $sql ) === TRUE) {
echo "temperature successfully stored" ;
} else {
echo "Error: " . $sql . "<br>" . $conn ->error;
}
$conn ->close();
?>
|
Output:
localhost/temp.php
- PHP code to perform abs() function by converting temperature negative to positive values
form1.php
PHP
<html>
<body>
<?php
$servername = "localhost" ;
$username = "root" ;
$password = "" ;
$dbname = "database" ;
$conn = new mysqli( $servername , $username , $password , $dbname );
echo "<br>" ;
echo "abs() demo" ;
echo "<br>" ;
echo "<br>" ;
$sql = "SELECT city,ABS(temperature) FROM temperature" ;
$result = $conn ->query( $sql );
while ( $row = mysqli_fetch_array( $result )){
echo " city id : " . $row [ 'city' ], " -- temperature : " . $row [ 'ABS(temperature)' ];
echo "<br>" ;
}
$conn ->close();
?>
</body>
</html>
|
Output :
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...