如何在SQL查询中插入PHP常量? [英] How do you insert a PHP constant into a SQL query?
问题描述
我有一个PHP文件,其数据库配置设置定义为常量,例如:
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);
?>
很明显,每当我想连接到数据库时,我都会包含上述文件.但是,当我将表定义常量插入SQL查询中时(见下文),它似乎不起作用.我需要适当地对常量进行转义还是以某种方式将其连接起来?
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";
推荐答案
您将不得不使用字符串连接(任何形式).
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')}";
这将执行constant()
函数并返回常量的值,但是,仅出于可读性考虑,这通常不是一个好主意.
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.
这篇关于如何在SQL查询中插入PHP常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!