Swoole\Coroutine\PostgreSQL->prepare(...)

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Coroutine\PostgreSQL->prepare(string $name, string $sql): void

Parameters

name

The name of the query, must be a unique name you can use to refer to query that is being prepared.

sql

The actual SQL query you want to prepare and then later execute.

Return

None


Description

Prepare a SQL statement and later execute it. This helps prevent SQL inject attacks, you should never trust data from unknown sources like a user, always prepare a statement and bind data to it.

When you prepare a statement you then use execute() to run the query, it's definition looks like this:

<?php
Swoole\Coroutine\PostgreSQL->execute(string $name, array $bind);
  • name: The unique name you gave the query when you prepared it.
  • bind: The array of data you want to bind to the query which also matches the placeholders in the SQL.

Example

<?php

use Swoole\Coroutine\PostgreSQL;

Co\run(function()
{
    $pg = new PostgreSQL();

    $conn = $pg->connect("host=127.0.0.1;port=5432;dbname=test;user=postgres;password=***");

    $pg->prepare("my_query", "select * from  test where id > $1 and id < $2");

    // Bind the array data to the placeholders in the query
    $res = $pg->execute("my_query", [1, 3]);

    $arr = $pg->fetchAll($res);

    var_dump($arr);
});
Last updated on August 31, 2022