帮我用php加mysql写一个游戏点卡管理系统,里面包括在页面上对数据进行删除,还有跳转页面新增点卡,最后在页面上验证提交
时间: 2024-03-19 22:43:15 浏览: 47
一个php+mysql的游戏代码
好的,我会尽力帮您完成这个任务。以下是代码实现:
1.连接数据库
```
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "cards";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
?>
```
2.查询数据
```
<?php
$sql = "SELECT id, card_name, card_price, card_stock FROM cards_info";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - 点卡名称: " . $row["card_name"]. " - 价格: " . $row["card_price"]. " - 库存: " . $row["card_stock"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
?>
```
3.插入数据
```
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$card_name = $_POST["card_name"];
$card_price = $_POST["card_price"];
$card_stock = $_POST["card_stock"];
$sql = "INSERT INTO cards_info (card_name, card_price, card_stock)
VALUES ('$card_name', '$card_price', '$card_stock')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
```
```
<!DOCTYPE html>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
点卡名称: <input type="text" name="card_name"><br>
价格: <input type="text" name="card_price"><br>
库存: <input type="text" name="card_stock"><br>
<input type="submit" value="新增">
</form>
</body>
</html>
```
4.删除数据
```
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$card_id = $_POST["card_id"];
$sql = "DELETE FROM cards_info WHERE id='$card_id'";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
```
```
<!DOCTYPE html>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
点卡ID: <input type="text" name="card_id"><br>
<input type="submit" value="删除">
</form>
</body>
</html>
```
5.验证提交
为了确保用户输入的数据是有效的,您可以使用PHP的过滤器来验证用户输入。以下是一个示例:
```
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$card_name = filter_var($_POST["card_name"], FILTER_SANITIZE_STRING);
$card_price = filter_var($_POST["card_price"], FILTER_SANITIZE_NUMBER_FLOAT);
$card_stock = filter_var($_POST["card_stock"], FILTER_SANITIZE_NUMBER_INT);
if (empty($card_name) || empty($card_price) || empty($card_stock)) {
echo "请填写所有字段";
} else {
$sql = "INSERT INTO cards_info (card_name, card_price, card_stock)
VALUES ('$card_name', '$card_price', '$card_stock')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
?>
```
请注意,这些示例代码仅供参考,并且需要根据您的具体情况进行修改和调整。
阅读全文