Build a PHP application

Install the php-pgsql driver

See instructions to install php-pgsql for your platform.

For example, for CentOS, use sudo yum install php-pgsql or Ubuntu use sudo apt-get install php-pgsql.

Sample PHP code

Create a file yb-sql-sample.php with the following content.

  1. <?php
  2. try {
  3. /* Establish connection. */
  4. $dbh = new PDO('pgsql:host=127.0.0.1;port=5433;dbname=yugabyte;user=yugabyte;password=yugabyte',
  5. 'yugabyte', null, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  6. PDO::ATTR_EMULATE_PREPARES => true,
  7. PDO::ATTR_PERSISTENT => true));
  8. /* Create the table if it doesn't exist. */
  9. $stmt = 'CREATE TABLE IF NOT EXISTS employee (id int PRIMARY KEY,
  10. name varchar,
  11. salary int,
  12. dept varchar)';
  13. $dbh->exec($stmt);
  14. /* Prepare the insert statement. */
  15. $insert_stmt = $dbh->prepare('INSERT INTO employee(id, name, salary, dept) ' .
  16. 'VALUES (:id, :name, :salary, :dept)');
  17. /* Insert a row. */
  18. $insert_stmt->bindValue(':id', 10, PDO::PARAM_INT);
  19. $insert_stmt->bindValue(':name', 'Jane', PDO::PARAM_STR);
  20. $insert_stmt->bindValue(':salary', 150000, PDO::PARAM_INT);
  21. $insert_stmt->bindValue(':dept', 'Engineering', PDO::PARAM_STR);
  22. $insert_stmt->execute();
  23. /* Insert a row. */
  24. $insert_stmt->bindValue(':id', 11, PDO::PARAM_INT);
  25. $insert_stmt->bindValue(':name', 'Joe', PDO::PARAM_STR);
  26. $insert_stmt->bindValue(':salary', 140000, PDO::PARAM_INT);
  27. $insert_stmt->bindValue(':dept', 'Finance', PDO::PARAM_STR);
  28. $insert_stmt->execute();
  29. echo "Inserted new records successfully.\n";
  30. /* Prepare query statement to retrieve user info by id */
  31. $query = $dbh->prepare('SELECT name, salary, dept FROM employee WHERE id = :id');
  32. $query->bindValue(':id', 11, PDO::PARAM_INT);
  33. $query->execute();
  34. $user_info = $query->fetch(PDO::FETCH_ASSOC);
  35. echo "Retrieving info for user id 11...\n";
  36. print_r($user_info);
  37. } catch (Exception $excp) {
  38. print "EXCEPTION: " . $excp->getMessage() . "\n";
  39. exit(1);
  40. }

Run the application

To run the application:

  1. $ php yb-sql-sample.php

and you should see the following output:

  1. Inserted new records successfully.
  2. Retrieving info for user id 11...
  3. Array
  4. (
  5. [name] => Joe
  6. [salary] => 140000
  7. [dept] => Finance
  8. )