How to Calculate the Percent of Change in PHP and MySQL
The PHP language lets you update any record in your MySQL tables. If you want to keep track of the percentage of change, you use the MySQL and PHP language together to calculate the percentage of change, then change the data according to your user input. This type of programming lets you keep track of the amount of change made to content or in customer shopping habits.
Instructions
-
-
1
Right-click the PHP page you want to use to update the data in your MySQL database and click "Open With" to select your PHP editor.
-
2
Create the connection to your MySQL database. Before you can update or calculate a rate of change, you must create a connection to the MySQL server with your username and password. The following code will connect to the server and the database:
mysql_connect("localhost", "phpuser", "password") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
The code above connects to the server "localhost" and uses the "mydb" for the database connection. If any errors occur, the "or die" statement returns the connection error to your PHP application. -
-
3
Create the query that retrieves the two database fields you want to use to perform the calculations. The following query retrieves the "content" field and the "previouscontent" field from the database table:
$records= mysql_query("select content, previouscontent from UserArticles")
or die(mysql_error());
$rows = mysql_fetch_array( $records); -
4
Determine the rate of change and assign the result to a variable in PHP. The following code determines the rate of change and assigns the results to the variable named "$result":
$result = $rows[0]/$rows[1]; -
5
Display the results on the webpage. The following code writes the results to the PHP webpage you chose earlier:
echo "Rate of change: " .$result
-
1