1

i'm having problems in executing a query inside php. I have the following query in my php code:

    $nome = pg_escape_string($_POST['cnome']);

$obtem_idb = "SELECT idb FROM banda WHERE nome = $nome";

echo("$nome");

$idb = pg_query($connection, $obtem_idb);
if(!$idb){
        die("Error in SQL query: " . pg_last_error());
    } else { 
echo("o idb que vem da query é $idb");
}

The name i print is correct, but when trying to execute the query i get the following error:

Error in SQL query: ERROR: column "anthrax" does not exist LINE 1: SELECT idb FROM banda WHERE nome = Anthrax ^

Can anyone help, i can't seem to find the error.

When i put the variable $nome in single quotes the value of it changes to 'Resource id #2' and i get the following error:

Error in SQL query: ERROR: insert or update on table "edicao" violates foreign key constraint "edicao_idb_fkey" DETAIL: Key (idb)=(Resource id #2) is not present in table "banda".

3 Answers 3

1

You've forgotten quotes around the value:

$obtem_idb = "SELECT idb FROM banda WHERE nome = '$nome'";
                                                 ^-----^--- must be quoted
Sign up to request clarification or add additional context in comments.

4 Comments

When i put nome in single quotes i get the following error: Resource id #2Error in SQL query: ERROR: insert or update on table "edicao" violates foreign key constraint "edicao_idb_fkey" DETAIL: Key (idb)=(Resource id #2) is not present in table "banda".
that's a whole other query causing that error. a select query can NOT produce a foreign key violation.
When i execute the query, the result that comes from it is "Resource id #2" and "B-7" as it should...
That's because a query() call returns a result HANDLE, not the data you've requested from the DB. You still have to actually FETCH a row of data and extract the value you want before you can insert that value into another query.
1

you need to quote $nome in your sql query

$obtem_idb = "SELECT idb FROM banda WHERE nome = '$nome'";

1 Comment

When i put nome in single quotes i get the following error: Resource id #2Error in SQL query: ERROR: insert or update on table "edicao" violates foreign key constraint "edicao_idb_fkey" DETAIL: Key (idb)=(Resource id #2) is not present in table "banda".
1

You need to put your $nome reference in single quotes:

$obtem_idb = "SELECT idb FROM banda WHERE nome = '$nome'";

1 Comment

When i put nome in single quotes i get the following error: Resource id #2Error in SQL query: ERROR: insert or update on table "edicao" violates foreign key constraint "edicao_idb_fkey" DETAIL: Key (idb)=(Resource id #2) is not present in table "banda".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.