Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

mysql - How do you insert a PHP constant into 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 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";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...