1

I am trying to write a PHP script to check if a table exists in Firebird, but because I have to use the dollar sign in the SQL, I get an error. Here is the code:

define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'\mobile\debug_mob_config.php');

$tableName = 'creadit_check';

// Check if the table exists
$query = "SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = :table_name";
$stmt = $DB->prepare($query);
$stmt->bindParam(':table_name', $tableName);
$stmt->execute();

$tableExists = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$tableExists) {
    // Create the table if it doesn't exist
    $createTableQuery = "
        CREATE TABLE $tableName (
            id INTEGER NOT NULL,
            name VARCHAR(255),
            PRIMARY KEY (id)
        )
    ";
    $DB->exec($createTableQuery);

    echo "Table '$tableName' created successfully.";
} else {
    echo "Table '$tableName' already exists.";
}

I have tried using the backquote to get round this but still get the error.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DaveLister
  • 127
  • 1
  • 9
  • @paulsm4 no need to escape a single quote within double quotes – Nick Aug 15 '23 at 01:16
  • If I'm understanding your problem correctly: all you need to do is quote your SQL strings with a SINGLE QUOTE (') instead of a double quote ("): `$query = 'SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = :table_name';`. See https://www.digitalocean.com/community/tutorials/how-to-work-with-strings-in-php – paulsm4 Aug 15 '23 at 05:39
  • I did try that but then I get the error ```error code = -206 Column unknown DB$RELATION_NAME ``` even though the statement is valid. – DaveLister Aug 15 '23 at 07:48
  • Please include the error in the question body. – Mark Rotteveel Aug 15 '23 at 10:20
  • 1
    In any case, you need to escape the `$` using `\$`. See [Strings, Double quoted](https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double), or use single-quoted strings. – Mark Rotteveel Aug 15 '23 at 10:22
  • Thanks you. Escaping the $ with a backslash worked :) – DaveLister Aug 15 '23 at 12:43

0 Answers0