PHP – My SQL : abs() – numeric function
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
- Start xampp server
- Create a database named database and create table named temperature.
- Write php code to insert records into the table.
temp.php
PHP
<?php //servername $servername = "localhost" ; //username $username = "root" ; //empty password $password = "" ; //database is the database name $dbname = "database" ; // Create connection by passing these connection parameters $conn = new mysqli( $servername , $username , $password , $dbname ); // Check this connection if ( $conn ->connect_error) { die ( "Connection failed: " . $conn ->connect_error); } //insert records into table $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 $servername = "localhost" ; //username $username = "root" ; //empty password $password = "" ; //database is the database name $dbname = "database" ; // Create connection by passing these connection parameters $conn = new mysqli( $servername , $username , $password , $dbname ); echo "<br>" ; echo "abs() demo" ; echo "<br>" ; echo "<br>" ; //sql query $sql = "SELECT city,ABS(temperature) FROM temperature" ; $result = $conn ->query( $sql ); //display data on web page while ( $row = mysqli_fetch_array( $result )){ echo " city id : " . $row [ 'city' ], " -- temperature : " . $row [ 'ABS(temperature)' ]; echo "<br>" ; } //close the connection $conn ->close(); ?> </body> </html> |
Output :