How do you insert a PHP constant into a SQL query?

前端 未结 4 2263
野性不改
野性不改 2020-12-18 05:34

I have a PHP file with my database configuration settings defined as constants, for example:



        
相关标签:
4条回答
  • 2020-12-18 05:39

    Just put it outside the quotes and it should work fine:

    $query = "SELECT users FROM ".DB_TABLE_1;
    
    0 讨论(0)
  • 2020-12-18 05:52

    You'll have to use string concatenation (of any sort).

    $query = "SELECT users FROM " . DB_TABLE_1;
    

    constants will not interpolate into a string as variables can.

    One hackish alternative is to use a variable function:

    $const = 'constant';
    $query = "SELECT users FROM {$const('DB_TABLE_1')}";
    

    which'll execute the constant() function and return the constant's value, but that's generally not a good idea, if only for legibility's sake.

    0 讨论(0)
  • 2020-12-18 05:53

    I think this is easier:

    $query = "SELECT users FROM '.DB_TABLE_1.'";
    

    when using multiple tables:

    $query = "SELECT TB_1.users, TB_2.names FROM '.TB_1.'
              INNER JOIN '.TB_2.' 
              ON x=y";
    

    Also, this is better:

    define("DB_HOST","localhost");
    
    0 讨论(0)
  • 2020-12-18 05:56

    I've found two ways.

    1.-

    define("VALUE1", "someValue");
    $query = "SELECT * FROM TABLE WHERE `Column` /*=" . VALUE1 . "*/";
    

    2.-

    define("VALUE1", "someValue");
    define("VALUE2", "otherValue");
    $query = "INSERT INTO TABLE (`Column1`, `Column2`) VALUES (" . VALUE1 . ", " . VALUE2 . ")";
    

    The backticks (``) I use because I'm using phpmyadmin, you might not need them.

    0 讨论(0)
提交回复
热议问题