在PHP中,我们可以使用PDO(PHP Data Objects)或者pgSQL扩展来操作PostgreSQL数据库,下面是使用PDO操作PostgreSQL的示例代码:
<?php // 连接数据库 $dsn = "pgsql:host=localhost;dbname=testdb"; $username = "postgres"; $password = "password"; try { $conn = new PDO($dsn, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo "连接失败: " . $e->getMessage(); } // 插入数据 $sql = "INSERT INTO users (username, email) VALUES (:username, :email)"; $stmt = $conn->prepare($sql); $stmt->bindParam(':username', $username); $stmt->bindParam(':email', $email); $stmt->execute(); // 查询数据 $sql = "SELECT * FROM users"; $stmt = $conn->query($sql); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "ID: " . $row["id"] . " Name: " . $row["name"] . " Email: " . $row["email"] . "<br>"; } ?>
下面是使用pgSQL扩展操作PostgreSQL的示例代码:
<?php // 连接数据库 $conn = pg_connect("host=localhost dbname=testdb user=postgres password=password"); if (!$conn) { die("Could not connect to database"); } else { echo "Connected successfully "; } // 插入数据 $sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')"; if (pg_query($conn, $sql)) { pg_close($conn); // Close connection if insert operation is successful.....!!!!!!!!!!!!!!!!!!!!!@@@@@@@@@@@@@@ &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&......................................................^^^^^^^^^^^^^^^^^^^^^^^^^^^^........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................@@@@@@@@@@@ @@@@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&@@@@@@@@@@@ &&&&&&&&&&&&&&&&&&&&& &&@@@@@@@ &&&@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@@@ &@@@*************************************************************************************************************************************012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567
还没有评论,来说两句吧...