In PHP, connecting to a database and executing SQL statements can be done through the following steps:
- Connect to database
Use mysqli_connect() Function or PDO Use a class to connect to a database. For example:
// 使用 mysqli 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// 使用 PDO 连接数据库
$dsn = "mysql:host=localhost;dbname=myDB";
$username = "username";
$password = "password";
// 创建连接
try {
$conn = new PDO($dsn, $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}- Execute an SQL statement
Use mysqli_query() Function or PDO generic query() A method for executing SQL statements. For example:
// 使用 mysqli 执行 SQL 语句
$sql = "SELECT * FROM myTable";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 输出数据
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
// 使用 PDO 执行 SQL 语句
$sql = "SELECT * FROM myTable";
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
// 输出数据
while($row = $result->fetch()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}The above describes the basic steps for connecting to a database and executing SQL statements; the specific implementation may vary depending on the context. It is important to prevent SQL injection attacks when executing SQL statements; this can be done using mysqli_real_escape_string() Function or PDO Use a preprocessing statement to avoid this situation.