PHP.mk документација

pg_query_params

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.pg-query-params.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.pg-query-params.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
pg_query_params

Референца за `function.pg-query-params.php` со подобрена типографија и навигација.

function.pg-query-params.php

pg_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_query_paramsSubmits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

= NULL

pg_query_params(PgSql\Connection $connection = ?, string $query, array $params): PgSql\Result|false

Поднесете команда до серверот и почекајте го резултатот, со можност за поминување параметри одделно од текстот на командата SQL

pg_query_params() Поднесете команда до серверот и почекајте го резултатот, со можност за поминување параметри одделно од текстот на командата SQL. pg_query()е како

, но нуди дополнителна функционалност: вредностите на параметрите можат да бидат специфицирани одделно од самиот команден стринг. query string as $1, $2, etc. The same parameter may appear more than once in the queryАко се користат параметри, тие се упатуваат во params ; истата вредност ќе се користи во тој случај. null специфицира вистинските вредности на параметрите. А NULL.

вредност во овој стринг значи дека соодветниот параметар е SQL pg_query_params() over pg_query() Главната предност на query е тоа што вредностите на параметрите можат да бидат одделени од pg_query(), pg_query_params() стринг, со што се избегнува потребата од досадно и склоно кон грешки цитирање и бегство. За разлика од

Параметри

connection

Еден PgSql\Connection инстанца. Кога connection не е наведено, се користи стандардната врска. Стандардната врска е последната врска направена од pg_connect() or pg_pconnect().

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Од PHP 8.1.0, користењето на стандардната врска е застарено.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

дозволува најмногу една SQL команда во дадениот стринг. (Може да има точки и запирки во него, но не повеќе од една непразна команда.) SQL инјекција Вредностите дадени од корисникот секогаш треба да се поминуваат како параметри, а не да се интерполираат во стринг за барање, каде што тие формираат можни Податоците во барањето треба да бидат.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

вектори на напади и воведуваат грешки при ракување со податоци што содржат цитати. Ако од некоја причина не можете да користите параметар, уверете се дека интерполираните вредности се bytea Вредностите наменети за pg_escape_bytea() полињата не се поддржани како параметри. Користете

Вратени вредности

Еден PgSql\Result инстанца при успех, или false при неуспех.

Дневник на промени

Верзија = NULL
8.1.0 Враќа PgSql\Result инстанца сега; претходно, а resource .
8.1.0 На connection параметарот очекува PgSql\Connection инстанца сега; претходно, а resource се очекуваше.

Примери

Пример #1 Користење pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets. Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?>

Види Исто така

  • pg_query() за да го одредите резултатот од барањето.

Белешки од корисници 14 белешки

наместо тоа, или користете ги функциите за големи објекти.
пред 14 години
You can't run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:

<?php
$connection = pg_connect("host=127.0.0.1 port=5432 dbname=foo user=bar password=baz");
pg_query($connection, 'DROP TABLE IF EXISTS example');
pg_query($connection, 'CREATE TABLE example (col char(1))');
pg_query($connection, 'INSERT INTO example (col) VALUES (\'a\')');
// 'SELECT col FROM example' in another session returns "a"
pg_query($connection, 'BEGIN');
pg_query_params($connection, 'UPDATE example SET col = $1', array('b'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query_params($connection, 'UPDATE example SET col = $1', array('c'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query($connection, 'COMMIT');
// 'SELECT col FROM example' in another session returns "c"
?>
php на richardneill точка org
пред 11 години
Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps:

<?php
$sql = "SELECT * from table WHERE col_a = $1 and col_b=$2 and col_c=$3";
$params = array (42, "a string", NULL);

$debug = preg_replace_callback( 
        '/\$(\d+)\b/',
        function($match) use ($params) { 
            $key=($match[1]-1); return ( is_null($params[$key])?'NULL':pg_escape_literal($params[$key]) ); 
        },
        $sql);

echo "$debug";
//prints:   SELECT * from table WHERE col_a = '42' and col_b='a string' and col_c=NULL
?>

This works correctly, except in the (unusual) case where we have a literal $N;  the regexp replaces it where it shouldn't.  For example:
<?php
//Both  ' ... $1 ... '   and  $1   get replaced; the former is wrong, the latter is right.
$sql = "SELECT 'Your bill is for $1' AS invoice WHERE 7 = $1";
$params = array(7);
//$debug:  SELECT 'Your bill is for $7' AS invoice WHERE 7 = '7'"
?>
victor dot engmark at terreactive dot ch
пред 16 години
pg_query and pg_query_params can be combined into a single function.  This also removes the need to construct a parameter array for pg_query_params:

<?php
function my_query($conn, $query)
{
  if(func_num_args() == 2)
    return pg_query($conn, $query);

  $args = func_get_args();
  $params = array_splice($args, 2);
  return pg_query_params($conn, $query, $params);
}
?>

Usage:

<?php
/* non-parameterized example */
my_query($conn, "SELECT $val1 + $val2");

/* parameterized example */
my_query($conn, "SELECT $1 + $2", $val1, $val2);
?>
jsnell на e-normous точка com
пред 18 години
When inserting into a pg column of type bool, you cannot supply a PHP type of bool.  You must instead use a string "t" or "f". PHP attempts to change boolean values supplied as parameters to strings, and then attempts to use a blank string for false.

Example of Failure:
pg_query_params('insert into table1 (bool_column) values ($1)', array(false));

Works:
pg_query_params('insert into lookup_permissions (system) values ($1)', array(false ? 't' : 'f'));
ac at esilo dot com
19 години пред
If you need to provide multiple possible values for a field in a select query, then the following will help.

<?php
// Assume that $values[] is an array containing the values you are interested in.
$values = array(1, 4, 5, 8);

// To select a variable number of arguments using pg_query() you can use:
$valuelist = implode(', ', $values);
$query = "SELECT * FROM table1 WHERE col1 IN ($valuelist)";
$result = pg_query($query)
    or die(pg_last_error());

// You may therefore assume that the following will work.
$query = 'SELECT * FROM table1 WHERE col1 IN ($1)';
$result = pg_query_params($query, array($valuelist))
    or die(pg_last_error());
// Produces error message: 'ERROR: invalid input syntax for integer'
// It only works when a SINGLE value specified.

// Instead you must use the following approach:
$valuelist = '{' . implode(', ', $values . '}'
$query = 'SELECT * FROM table1 WHERE col1 = ANY ($1)';
$result = pg_query_params($query, array($valuelist));
?>

The error produced in this example is generated by PostGreSQL.

The last method works by creating a SQL array containing the desired values. 'IN (...)' and ' = ANY (...)' are equivalent, but ANY is for working with arrays, and IN is for working with simple lists.
петар точка кехл+nospam на gmail точка ком
пред 13 години
Third parameter $params of pg_query_params() ignores nay part of the string values after a zero byte character - PHP "\0" or chr(0). That may be a result of serialize().

See https://bugs.php.net/bug.php?id=63344
алек на smecher точка bc точка ca
пред 13 години
Note that due to your locale's number formatting settings, you may not be able to pass a numeric value in as a parameter and have it arrive in PostgreSQL still a number.

If your system locale uses "," as a decimal separator, the following will result in a database error:

pg_query_params($conn, 'SELECT $1::numeric', array(3.5));

For this to work, it's necessary to manually convert 3.5 to a string using e.g. number_format.

(I filed this as bug #46408, but apparently it's expected behavior.)
akashwebdev at gmail dot com
пред 16 години
Regarding boolean values, just typecast them as (integer) when passing them in your query -- '0' and '1' are perfectly acceptable literals for SQL boolean input:

- http://www.postgresql.org/docs/8.2/interactive/datatype-boolean.html

It is also safe to write your paramerized query in double-quotes, which allows you to mix constant values and placeholders in your query without having to worry about how whether PHP will attempt to substitute any variables in your parameterized string.

Of course this also means that unlike PHP's double-quoted string syntax, you CAN include literal $1, $2, etc. inside SQL strings, e.g:

<?php
// Works ($1 is a placeholder, $2 is meant literally)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1));

// Throws an E_WARNING (passing too many parameters)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1, $data2));
?>
mledford
19 години пред
If you are trying to replicate the function pg_query_params, you might also want to support NULL values. While is_int returns true for a NULL value, the formatting for the SQL.

function pg_query_params( $db, $query, $parameters ) {
    // Escape parameters as required & build parameters for callback function
    global $pg_query_params__parameters;
    foreach( $parameters as $k=>$v ) {
        if ( is_null($v) ) {
            $parameters[$k] = 'NULL';
        } else {
            $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
        }
    }
    $pg_query_params__parameters = $parameters;
        
    // Call using pg_query
    return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query));
}
cc+php на c2se точка com
19 години пред
This is a useful function for preventing SQL injection attacks, so, for those of us who are not yet able to upgrade to PHP5.1, here is a replacement function which works similarly on older versions of PHP...

<?php   # Parameterised query implementation for Postgresql and older versions of PHP

        if( !function_exists( 'pg_query_params' ) ) {

                function pg_query_params__callback( $at ) {
                        global $pg_query_params__parameters;
                        return $pg_query_params__parameters[ $at[1]-1 ];
                }

                function pg_query_params( $db, $query, $parameters ) {

                        // Escape parameters as required & build parameters for callback function
                        global $pg_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
                        $pg_query_params__parameters = $parameters;

                        // Call using pg_query
                        return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query ) );

                }
        }

        // Example: pg_query_params( $db_resource, "SELECT * FROM table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );
?>
Анонимен
пред 9 години
If one of the parameters is an array,  (eg. array of ints being passed to a stored procedure),   it must be denoted as a set within the array,  not php array notation.  

eg:  var_dump output  of 2 parms an integer and array of int
aaa is: Array
(
    [0] => 1
    [1] => {2,3}
)

you do not want:

bbb is: Array
(
    [0] => 1
    [1] => Array
        (
            [0] => 2
            [1] => 3
        )

)
php на richardneill точка org
пред 11 години
pg_query_params() *does* accept NULLs.  They will automatically be transformed, correctly, into SQL NULL. Thus, for example:

<?php
$sql = "UPDATE tbl_example SET column_a = $1, column_b=$2";
$params = array(NULL,  42);
$result = pg_params ($sql, $params);

//is equivalent to:
$result = pg_query ("UPDATE tbl_example SET column_a = NULL column_b  = '42')";

//and not, as one might fear,  either of these (incorrect) things:
// ... column_a = ''      ...
// ... column_a = 'NULL'  ...
?>

Note that you can use NULLs this way in an UPDATE or INSERT statement, but NOT in a WHERE clause. This isn't a restriction of pg_query_params(), but rather it is a consquence of the SQL language.
So, if you want a query of the type:

<?php
//depending on data,  the where-test parameter may or may not be NULL
//the following is WRONG for $1.
$sql = "SELECT * from  tbl_example WHERE column_a = $1 and column_b = $2";
$params = array(NULL,  42);
$result = pg_params ($sql, $params);
?>

This will fail as invalid SQL:  because you should use "= 42" but "IS NULL".  The solution is to use the SQL construct "IS [NOT] DISTINCT FROM".  

<?php
$sql = "SELECT ... WHERE column IS NOT DISTINCT FROM $1"
$params = array (42);    //this works, the same as  "where column = 42"
$params = array (NULL);  //this works, the same as "where column is null"
?>

(Aside: though this is annoying, the behaviour is correct. There is a postgresql compatibility option "transform_null_equals", but it won't help you here, even though you might expect it to.)
php на richardneill точка org
пред 11 години
A note on type-juggling of booleans:
pg_query_params() and friends do seamless, automatic conversion between PHP-NULL and SQL-NULL and back again, where appropriate.
Hoever, everything else goes in (and comes out) as a string.
The following approach may be helpful when handling boolean fields:

<?php
$sql = " ... ";
$params = array (1, 2, 3, true, false);

//Convert booleans to 'true' and 'false'.  [NULLS are already handled].
foreach ($params as &$value){
    if (is_bool($value)){
        $value = ($value) ? 'true':'false';
    }
}

//Now do the query:
$result = pg_query_params ($sql, $params);
$row = pg_fetch_assoc ($result,0)  //first row

//For booleans, convert 't' and 'f' back to true and false. Check the column type so we don't accidentally convert the wrong thing.
foreach ($row as $key => &$value){ 
    $type = pg_field_type($result,pg_field_num($result, $key));
    if ($type == 'bool'){
        $value = ($value == 't');
    }
}

//$row[] now contains booleans, NULLS, and strings.
?>
php на richardneill точка org
пред 11 години
For a parameterised date, the value NOW() is not allowed (it gets turned into a literal string and makes postgres choke),  however 'now'
is allowed as a parameter, and has the same effect.
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.