<code class="php"><?php $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database_name"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?></code>>插入新记录,使用准备好的语句的插入查询来防止SQL注入漏洞。
>
3。读取(选择):<code class="php"><?php $sql = "INSERT INTO users (name, email) VALUES (?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("ss", $name, $email); // "ss" specifies two string parameters $name = "John Doe"; $email = "john.doe@example.com"; $stmt->execute(); if ($stmt->affected_rows > 0) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $stmt->close(); ?></code>
要检索数据,请使用SELECT查询。 同样,即使您不使用Whey子句中的用户提供的数据,也建议使用准备好的语句,以确保一致性和最佳实践。更新(Update):
要修改现有记录,请使用准备好的语句使用更新查询。删除(删除):<code class="php"><?php $sql = "SELECT id, name, email FROM users WHERE id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("i", $id); // "i" specifies an integer parameter $id = 1; $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 results"; } $stmt->close(); ?></code>
>要删除记录,使用准备好的语句的删除查询。>
<code class="php"><?php $sql = "UPDATE users SET name = ?, email = ? WHERE id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("ssi", $name, $email, $id); $name = "Jane Doe"; $email = "jane.doe@example.com"; $id = 1; $stmt->execute(); if ($stmt->affected_rows > 0) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $stmt->close(); ?></code>>在php 7应用中确保CRUD操作的最佳实践是什么? (CSRF)。以下是一些最佳实践:
htmlspecialchars()
永远不要相信用户输入。在查询中使用或在页面上显示所有数据之前,请先验证和消毒。 使用is_numeric()
之类的功能来防止XSS攻击。 对于数据类型验证,请使用适当的PHP函数(例如,filter_var()
)。htmlspecialchars()
输出编码:json_encode()
用于HTML上下文,EXPLAIN
分析您对效率低下的查询。使用SELECT *
(MySQL)或类似工具来了解数据库如何执行您的查询。 避免>
常见错误在PHP 7中实现CRUD操作时bind_param()
try-catch
>块(或等效)来处理异常和日志错误。>调试技术:
print_r()
>使用这些功能来检查变量和数据结构的值。以上是如何在PHP 7中执行CRUD操作(创建,阅读,更新,删除)?的详细内容。更多信息请关注PHP中文网其他相关文章!