今天搞一下PHP操纵MySQL,做个小笔记。
1.使用MySQL命令行
可以打开phpstudy点开MySQL服务,也可以cmd下进入到MySQL下bin目录中,输入net start mysql
2.使用PHP连接服务器、创建数据库、数据表、插入一条或多条数据等
具体代码就不详细说了,注意主机名。用户名和密码写对就可以了。
3.PHP预处理语句(可降低SQL注入的风险)
因为sql注入是因为动态字符串的拼接导致sql命令发生改变,然后编译并且执行错误的结果。
而sql预处理则是提前“告诉”sql语法处理器,提前声明并且编译特定格式的sql语句,然后将所有用户的输入视为纯字符串参数,最后组成查询语句。
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "新记录插入成功";
$stmt->close();
$conn->close();
?>
预处理语句模板: "INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)"
例如: $stmt = $conn->prepare(“INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)”); $stmt->bind_param(“sss”, $firstname, $lastname, $email);
bind_param() 函数:绑定了 SQL 的参数,且告诉数据库参数的值。 “sss” 参数列处理其余参数的数据类型。s 字符告诉数据库该参数为字符串。
参数有以下四种类型:
i - integer(整型)
d - double(双精度浮点型)
s - string(字符串)
b - BLOB(binary large object:二进制大对象)
|