在定义后在字符串中插入变量

时间:2017-05-07 13:26:36

标签: php sql

是否可以做这样的事情:

SQL = 'SELECT * FROM test_table ' .$sqljoin . $where . $order;
if (a>0){
$sqljoin = 'INNER JOIN test_users ON test_opplegg.UserId = test_users.id';
}else{
$where = 'WHERE target=1'
}

//Add the new variable to the SQL-sentence...

然后将新变量添加到SQL语句中。这样我就不需要多次编写SQL语句了,我可以在SQL定义开始后添加值吗?

2 个答案:

答案 0 :(得分:1)

你会想要这样的东西:

$order = 'ORDER BY column_name ASC' //or DESC

if ($a>0)
{
    $sql_append = 'INNER JOIN test_users ON test_opplegg.UserId = test_users.id';
}
else
{
    $sql_append = 'WHERE target=1'
}

$sql = 'SELECT * FROM test_table ' . $sql_append . $order;

答案 1 :(得分:0)

使用string formatting

// I assume you have already defined $order somewhere before this

$sql = 'SELECT * FROM test_table %s %s %s';

$sqljoin = '';
$where = '';

if (a>0){
    $sqljoin = 'INNER JOIN test_users ON test_opplegg.UserId = test_users.id';
}else{
    $where = 'WHERE target=1'
}

$sql = sprintf($sql, $sqljoin, $where, $order);