0
0
PHPprogramming~30 mins

Transaction management in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Transaction management
📖 Scenario: You are building a simple PHP script to manage a bank account transaction. You want to make sure that money is only withdrawn if there is enough balance, and if something goes wrong, the transaction should be canceled.
🎯 Goal: Create a PHP script that uses transaction management to safely withdraw money from a bank account balance stored in a variable.
📋 What You'll Learn
Create a variable $balance with the initial amount of 1000
Create a variable $withdraw with the amount to withdraw, 300
Use transaction management with try and catch blocks
Check if $balance is enough for the withdrawal
If enough, subtract $withdraw from $balance
If not enough, throw an exception with message 'Insufficient funds'
Print the final balance or the error message
💡 Why This Matters
🌍 Real World
Transaction management is important in banking and shopping websites to keep data safe and consistent.
💼 Career
Understanding how to use transactions and error handling is a key skill for backend developers working with databases.
Progress0 / 4 steps
1
Set up initial balance and withdrawal amount
Create a variable called $balance and set it to 1000. Then create a variable called $withdraw and set it to 300.
PHP
Need a hint?

Use simple variable assignment like $balance = 1000;

2
Start transaction with try block
Add a try block to start the transaction management. Inside it, write a comment // Transaction starts.
PHP
Need a hint?

Use try { } to start the transaction block.

3
Check balance and update inside try block
Inside the try block, write an if statement to check if $balance is greater than or equal to $withdraw. If yes, subtract $withdraw from $balance. Otherwise, throw a new Exception with the message 'Insufficient funds'. Add a catch block to catch Exception as $e.
PHP
Need a hint?

Use throw new Exception('Insufficient funds'); to stop the transaction if balance is low.

4
Print the final balance or error message
After the try-catch block, write an if statement to check if $error is set. If yes, print 'Error: ' followed by $error. Otherwise, print 'Final balance: ' followed by $balance.
PHP
Need a hint?

Use print("Final balance: $balance\n"); to show the result.