繁体   English   中英

如何从MySQL结果中回显PHP变量

[英]How to echo a PHP variable from MySQL results

为了自动化我的PHP生成JSON,我在数据库中保存了变量的名称(例如> $test_value_1 )。

在我的php文件中,我有这个变量的值(例如> $test_value_1 = "TEST VALUE 1"

在此之后,我执行查询以回显此变量,但是,不是返回变量的值(TEST VALUE 1),而是始终只返回数据库中的文本保存(“$ teste_value_1”)

要更好地理解,请查看我的数据库,变量,查询,响应以及我需要的内容:

表:属性

   id_attribute |  attribue_string | attribute_value
    1            |  test_string_1  | $test_value_1
    2            |  test_string_2  | $test_value_2

变量:

$test_value_1 = "Test Value 1"; 
$test_value_2 = "Teste Value 2";

查询:

$query_array = mysqli_query($connect,"
    SELECT GROUP_CONCAT(CONCAT('{id:', a.attribute_string, ',value_name:', a.attribute_value, '}') SEPARATOR ', ') AS concat
    FROM rel_categories_attributes AS rca
    INNER JOIN categories AS c ON c.id_category = rca.categories_id_category
    INNER JOIN attributes AS a ON a.id_attribute = rca.attributes_id_attribute
    WHERE id_category = '{$id_category}'
    ");
WHILE ($reg_cat = mysqli_fetch_array($query_array)){

    echo $teste_query = $reg_cat["concat"] . ",";

回复: {id:test_string_1,value_name:$test_value_1}, {id:teste_string_2,value_name:$test_value_2} ,(错误)

我需要什么: {id:test_string_1,value_name:TEST VALUE 1}, {id:teste_string_2,value_name:TESTE VALUE 2}

虽然这看起来像一个可怕的设计,你可以使用变量变量 但是你需要在PHP中进行输出格式化,而不是在MySQL中。

$query_array = mysqli_query($connect,"
    SELECT a.attribute_string, a.attribute_value
    FROM rel_categories_attributes AS rca
    INNER JOIN categories AS c ON c.id_category = rca.categories_id_category
    INNER JOIN attributes AS a ON a.id_attribute = rca.attributes_id_attribute
    WHERE id_category = '{$id_category}'
");

$result = array();
while ($row = mysqli_fetch_assoc($query_array) {
    $result[] = array('id' => $row['attribute_string'], 'value_name' => ${$row['attribute_value']});
}
echo json_encode($result);

但是,通过使用关联数组,几乎总能改进变量变量。 不要使用$test_value_1$test_value_2等变量,而是创建一个键为"test_value_1""test_value_2" $array[$row['attribute_value']] ,然后使用$array[$row['attribute_value']]

但更好的方法是将所有细节都放在数据库本身,而不是在脚本中对它们进行硬编码。 然后,您可以与该表联接以将属性值转换为适当的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM