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

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\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
OpenSwoole\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 OpenSwoole\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 September 1, 2022