Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

mysql

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

<?php

define(DB_HOST,"localhost");
define(DB_USERNAME,"root");
define(DB_PASSWORD,"password");
define(DB_NAME,"db_users");
define(DB_TABLE_1,"table_1");
define(DB_TABLE_2,"table_2);

?>

I obviously include the above file whenever I want to connect to my database..However, when I go to insert the table definition constants into the SQL query (see below) it doesn't seem to work. Do I need to properly escape the constant or concatenate it in some way?

$query = "SELECT users FROM DB_TABLE_1";
like image 434
Alexa Green Avatar asked Jan 16 '12 17:01

Alexa Green


2 Answers

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.

like image 78
Marc B Avatar answered Sep 23 '22 19:09

Marc B


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

$query = "SELECT users FROM ".DB_TABLE_1;
like image 41
Tim Withers Avatar answered Sep 25 '22 19:09

Tim Withers