我可以从mysql表中获取值并将其设置为变量吗?

时间:2019-06-28 11:22:49

标签: php mysql mysqli

attribute_description

我在图像中有attribute_description:

我在表中拥有cap_tabel值:d, lt, lu, amb, coada

我想获取它们并使它可变,并将值设置为等于attribute_id。

例如:

$d = 1; 
$lt = 2; 
$coada = 9;

我认为我可以在创建此变量的地方创建一个function.php文件,并在需要的地方使用它们。

这是可能的,还是我必须创建一个脚本,在其中我自己命名该变量并将其设置为正确的值,例如:

$amb_ext = mysqli_fetch_array(mysqli_query($connect,"SELECT attribute_id FROM attribute_description WHERE cap_tabel='amb'"));
$amb = $amb_ext['attribute_id'];

您认为什么是最好的解决方案?

最后,我想创建一个产品表,其中th中的值将是cap_tabel中的值,而td中的值将是正确的th单元格的值

2 个答案:

答案 0 :(得分:-1)

您可以使用variable variables

$res = mysqli_query($connect,"SELECT attribute_id, cap_tabel FROM attribute_description");
while ($row = $res->fetch_assoc()) {
    $var = $row['cap_tabel'];
    $$var = $row['attribute_id'];
}
// you now would have variables $d, $lt, etc

答案 1 :(得分:-1)

$result = mysqli_query($connect,"SELECT attribute_id, cap_tabel FROM attribute_description");

while ($aValue =  mysqli_fetch_array($result)) {
    ${$aValue['cap_tabel']} = $aValue['attribute_id'];
}

echo ' $d = ' . $d . ', $lt = ' . $lt . ', $coada = ' . $coada;

要获得这样的结果:

$d = 1, $lt = 2, $coada = 9