Board logo

標題: PHP 透過 PDO 操作 pgsql [打印本頁]

作者: ray    時間: 2020-6-13 10:46     標題: PHP 透過 PDO 操作 pgsql

本帖最後由 ray 於 2020-6-13 11:35 編輯

https://www.postgresqltutorial.com/postgresql-php/

Connect:
$conStr = "pgsql:host=[host];port=5432;dbname=[db];user=[user];password=[password]";
$pdo = new \PDO($conStr);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

Insert:
$sql = 'INSERT INTO usertb(uname,pass) VALUES(:uname,:pass)';
$stmt = $pdo->prepare($sql);

// pass values to the statement
$stmt->bindValue(':uname', "hello");
$stmt->bindValue(':pass', "hello");

// execute the insert statement
$stmt->execute();

// return generated id
echo $pdo->lastInsertId();

Select:
$stmt = $pdo->query('SELECT uname, pass FROM usertb');
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC))
    echo $row['uname'].",".$row['pass']."<br>";
作者: ray    時間: 2020-6-13 11:54

  1. <!DOCTYPE html>
  2. <html lang="en">

  3. <head>
  4.     <meta charset="utf-8">
  5.     <title>test</title>
  6. </head>

  7. <body>
  8. This is firt test<br>
  9. <?php
  10. $conStr = "pgsql:host=ec2-34-198-243-120.compute-1.amazonaws.com;port=5432;dbname=d33tv102tftng6;user=zdnbsjhbujtaca;password=4e00d5400a3b2f211a31dae4b7b679212d0e7c72763659cd5337b6e8b1f4227e";
  11. $pdo = new \PDO($conStr);
  12. $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

  13. if(isset($_POST["uname"]) && isset($_POST["password"]) && $_POST["uname"] != "" && $_POST["password"] != "")
  14. {
  15.         $sql = 'INSERT INTO usertb(uname,pass) VALUES(:uname,:pass)';
  16.         $stmt = $pdo->prepare($sql);

  17.         // pass values to the statement
  18.         $stmt->bindValue(':uname', $_POST["uname"]);
  19.         $stmt->bindValue(':pass', $_POST["password"] );

  20.         // execute the insert statement
  21.         $stmt->execute();

  22.         // return generated id
  23.         //echo $pdo->lastInsertId();
  24. }
  25. $stmt = $pdo->query('SELECT uname, pass FROM usertb');
  26. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC))
  27.     echo $row['uname'].",".$row['pass']."<br>";
  28. ?>
  29. <form action="" method="post">
  30. Account:<input type=text name=uname><br>
  31. Password:<input type=password name=password><br>
  32. <input type=submit value='insert'>
  33. </form>
  34. </body>
  35. </html>
複製代碼





歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://seed.istak.org.tw/) Powered by Discuz! 7.2