下面是一个使用 PHP 连接 SQL Server 数据库,并实现增删改查操作的示例代码,其中使用了 PDO 扩展:
$host = 'hostname'; $dbname = 'database_name'; $username = 'username'; $password = 'password'; $dsn = "sqlsrv:Server=$host;Database=$dbname"; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 1 ); try { $conn = new PDO($dsn, $username, $password, $options); // Insert operation $insertQuery = "INSERT INTO myTable (column1, column2) VALUES (?, ?)"; $stmt = $conn->prepare($insertQuery); $stmt->execute(array("some value", 123)); echo "Rows affected by insert operation: " . $stmt->rowCount() . "\n"; // Update operation $updateQuery = "UPDATE myTable SET column1 = ? WHERE column2 = ?"; $stmt = $conn->prepare($updateQuery); $stmt->execute(array("new value", 123)); echo "Rows affected by update operation: " . $stmt->rowCount() . "\n"; // Delete operation $deleteQuery = "DELETE FROM myTable WHERE column2 = ?"; $stmt = $conn->prepare($deleteQuery); $stmt->execute(array(123)); echo "Rows affected by delete operation: " . $stmt->rowCount() . "\n"; // Select operation $selectQuery = "SELECT * FROM myTable"; $stmt = $conn->query($selectQuery); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "column1: " . $row['column1'] . ", column2: " . $row['column2'] . "\n"; } } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
在上述代码中,使用 PDO 扩展创建一个与 SQL Server 数据库建立连接的对象,并依次执行插入、更新、删除和查询操作。在每个操作中,使用 prepare()
方法准备 SQL 语句,并使用占位符保护代码免受 SQL 注入攻击。然后,使用 execute()
方法将实际值传递给占位符并执行 SQL 语句。最后,使用 query()
和 fetch()
方法执行 SELECT 查询,并输出结果。
需要注意的是,这只是一个示例代码,实际应用中可能需要更多的错误处理和数据验证等功能。
评论