How to insert a PHP constant in a SQL query?

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 when I want to connect to my database. However, when I move on to inserting table definition constants into the SQL query (see below), it does not seem to work. Should I properly avoid the constant or concatenate it somehow?

$query = "SELECT users FROM DB_TABLE_1";
+5
source share
4 answers

You will need to use string concatenation (of any type).

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

will not interpolate to string as variables.

One of the hacker alternatives is to use a variable function:

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

constant() , , , , .

+15

, :

$query = "SELECT users FROM ".DB_TABLE_1;
+3

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
source

I 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 inverse elements (``) I use because I use phpmyadmin you may not need.

0
source

All Articles