take the status of pg_query and pass to php variable

Asked

Viewed 370 times

3

Imagine the following consultation:

pg_query($conn,"selects * from tabela");

Considering there’s a mistake in selects,

'ERROR: syntax error at or near "selects" LINE 1: selects * from table... ^'

How can I get this result and move to a php variable?

I tested it in the following ways, but without success:

1

$sql = 'selects * from table'
if(pg_query($conn,$sql)) $res = 'ok'; else $res = pg_last_error($conn);

2

$sql = pg_query($conn,"selects * from table");
if($sql) $res = 'ok'; else $res = pg_result_status($sql);

3

$sql = pg_query($conn,"selects * from table");
if(pg_affected_rows($sql)>0) $res = 'ok'; else $res = pg_result_status($sql);

4

$sql = pg_query($conn,"selects * from table");
if(pg_affected_rows($sql)>0) $res = 'ok'; else $res = pg_last_result($conn);
  • I do not understand very well what you want, want to store in a variable the error message?

  • @Andréfilipe, that’s right.

  • Just a curiosity: Why are you trying to force this error, why not execute the comment correctly?

  • @Andréfilipe, I’m not forcing, sometimes you have a clerical error typing the code and I want to record that information, that’s all

  • It is SELECT and not SELECTS. Take this s from the end.

  • @anonymity, did not read the question carefully...

Show 1 more comment

1 answer

1


The command pg_last_error gets the last error message string of a connection, so it is necessary to pass the connection string.

echo pg_last_error($conn);

For example the code below:

<?php

// Variável de Conexão com o banco
$conn = pg_connect("host=127.0.0.1 port=5432 dbname=sistema user=luiz-justino password=#seTTT#323") or die("Não foi possível conectar ao servidor PostGreSQL");

// Query
$sql = "SELECTS * FROM tb_cliente c WHERE c.id = 7";
// Executa a query
$result = pg_query($conn, $sql);

// O comando abaixo exibirá o erro desta última query na conexão $conn
echo pg_last_error($conn);

The message that will appear is that the syntax of the command is wrong (because the right is select instead of selects): (as my php is configured to display warnings is already showing the error, but the capture of this error is on the line marked which is the one I gave an echo using the function echo pg_last_error($conn);) inserir a descrição da imagem aqui

For when the pg_query it has two possible returns: a query result feature in case of success or FALSE in case of failure. If an error occurs and FALSE is returned, details of the error can be recovered using the pg_last_error() function if the connection is valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.