【问题标题】:Can I get value from mysql table and set it as variable?我可以从 mysql 表中获取值并将其设置为变量吗?
【发布时间】:2019-06-28 11:22:49
【问题描述】:

我有图片中的属性描述:

在桌子上我有 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_tabeltd 以使用正确的th 单元格获得正确的值

【问题讨论】:

  • 它不仅是最好的解决方案,而且是唯一的解决方案。

标签: php mysql mysqli


【解决方案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

【讨论】:

    【解决方案2】:
    $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
    

    【讨论】:

    • mysqli_fetch_array 将返回一个数组,在您的示例中,您将无法在 $oData 上执行 fetch_assoc()。顺便说一句,这与我的答案非常相似,但我被否决了:(
    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 2014-01-02
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2012-06-10
    相关资源
    最近更新 更多