First of all, we need to ensure that we have installed PHP and MySQL correctly, and have established a MySQL database that can accept user recharges. Administrators of our database can use the MySQL command line or any MySQL GUI tool.
We can start writing PHP scripts to query the database once we are sure it can accept top-ups. We will start by creating a simple HTML form so that the user can enter the amount they want to top up and send it to a PHP script. The following is a simple example form:
<form action="recharge.php" method="post"> <label for="amount">Amount:</label> <input type="text" name="amount" id="amount"> <button type="submit">Recharge</button> </form>
When the user submits the form, we will use a PHP script to handle the recharge request. This is a short PHP script for processing received form data and storing the data in a MySQL database
<?php //连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); //检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //处理表单数据 $amount = $_POST["amount"]; //将充值金额添加到数据库 $sql = "UPDATE users SET balance = balance + $amount WHERE id = 1"; if ($conn->query($sql) === TRUE) { echo "Recharge successful"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
In the above script, we first established an object connected to the MySQL database, and Verified that the connection operation was successful. Next, we will extract the recharge amount from the table data, and then add it to the database using UPDATE query. Finally, we print the result message and close the connection.
We can run the above code to observe that the recharge amount has been added to the MySQL database and the user balance has been updated. This is a very basic example and may require more security and error handling code, but it should be enough to get you started with a deeper understanding of how to use PHP to query MySQL to handle user top-ups.
The above is the detailed content of How PHP handles user recharge by querying MySQL. For more information, please follow other related articles on the PHP Chinese website!