duanchao1002 2014-05-15 20:16
浏览 47
已采纳

PHP:检索两个最新的mySQL表条目并将每个条目存储在不同的变量中

Please see the below code.

I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.

Does anyone know please how I can get them into two separate variables instead?

Thanks!

//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");

// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}

//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');

//Process the results
if  (mysqli_num_rows($result) > 0) {
while   (  $dataValue = mysqli_fetch_row($result))

    echo "<p>".$dataValue[0]."</p>";   
}
  • 写回答

1条回答 默认 最新

  • donglian4770 2014-05-15 20:20
    关注

    Change :

    while ($dataValue = mysqli_fetch_row($result))
    
        echo "<p>".$dataValue[0]."</p>"; 
    

    To this :

    $values = null;
    while ($dataValue = mysqli_fetch_assoc($result))
    {
        $values[] = $dataValue['element_value'];
    }
    
    print_r($values);
    

    This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.

    If you want to display them in an array again, you can do this :

    foreach ($values as $value)
    {
        echo "<p>".$value."</p>"; 
    }
    

    I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧