PHP常用的小程序代码段
1. 连接MySQL数据库
代码段
<?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); } echo "Connected successfully"; ?>
2. 插入数据到MySQL数据库
代码段
<?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); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn>query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn>error; } $conn>close(); ?>
3. 从MySQL数据库查询数据
代码段
<?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); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn>query($sql); if ($result>num_rows > 0) { // 输出数据 while($row = $result>fetch_assoc()) { echo "id: " . $row["id"]. " Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; } $conn>close(); ?>
4. 更新MySQL数据库中的数据
代码段
<?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); } $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if ($conn>query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn>error; } $conn>close(); ?>
5. 删除MySQL数据库中的数据
代码段
<?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); } $sql = "DELETE FROM MyGuests WHERE id=3"; if ($conn>query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn>error; } $conn>close(); ?>
相关问题与解答
问题1:如何在PHP中防止SQL注入?
回答:在PHP中防止SQL注入的常用方法是使用预处理语句(prepared statements)和绑定参数,预处理语句确保了SQL语句的结构在执行前已经固定,从而避免了恶意输入对数据库结构的影响,使用mysqli
或PDO
扩展来创建预处理语句。
问题2:如何优化数据库查询性能?
回答:优化数据库查询性能可以从多个方面入手,包括索引的使用、查询语句的优化、减少返回的数据量等,合理地设计数据库表结构,为经常需要查询的列添加索引可以显著提高查询效率,避免在查询中使用复杂的计算和函数,尽量简化查询逻辑,也是提升性能的有效方法。
以上就是关于“PHP常用的小程序代码段”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!