Introduction - Query

Introduction - Query – Performing queries

Description

PEAR DB provides several methods for querying databases. The most direct method is query(). It takes a SQL query string as an argument. There are three possible returns: a new DB_result object for queries that return results (such as SELECT queries), DB_OK for queries that manipulate data (such as INSERT queries) or a DB_Error object on failure.

Doing a query

<?php
// Create a valid DB object named $db
// at the beginning of your program...
require_once 'DB.php';

$db =& DB::connect('pgsql://usr:pw@localhost/dbnam');
if (
PEAR::isError($db)) {
    die(
$db->getMessage());
}

// Proceed with a query...
$res =& $db->query('SELECT * FROM clients');

// Always check that result is not an error
if (PEAR::isError($res)) {
    die(
$res->getMessage());
}
?>

query() can be used instead of prepare() and execute(), if you set the $params parameter and your query uses placeholders.

Using query in prepare/execute mode with a scalar parameter

<?php
// Once you have a valid DB object named $db...
$sql  'select * from clients where clientid = ?';
$data 53;

$res =& $db->query($sql$data);

// Always check that result is not an error
if (PEAR::isError($res)) {
    die(
$res->getMessage());
}
?>

Using query in prepare/execute mode with an array parameter

<?php
// Once you have a valid DB object named $db...
$sql  'select * from clients where clientid = ? and statusid = ?';
$data = array(534);

$res =& $db->query($sql$data);

// Always check that result is not an error
if (PEAR::isError($res)) {
    die(
$res->getMessage());
}
?>
Connecting and disconnecting a database (Previous) Obtaining data from query results (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

There are no user contributed notes for this page.