dongque4778 2014-02-14 02:13
浏览 65
已采纳

将数据库放入数组并使用foreach语句和Opencart在外部使用它

I have seen the opencart function which can be used outside with html like

<?php

    foreach ($categories as $category){
        echo $category['image'];
    }

?>

i would like to make a function like that in php which i can grab data from database and use it outside. may be it's an array so foreach statement is working on it.

like i have name and age in my database i would like to use it like this

<?php
    foreach($peoples as $people){
        echo $people['name'];
        echo $people['age'];
    } 
?>

Thanks in advance

  • 写回答

2条回答 默认 最新

  • douleijiang8111 2014-02-14 04:43
    关注

    As Aman Chhabra mentioned, you must first fetch the result from database and then you can use foreach loop to iterate over it. One thing I would like to mention is DON'T use mysql_query() as use of it is discouraged as per the new guidelines of php development (Check: http://ca1.php.net/manual/en/function.mysql-query.php). To have a compatible code with advanced php use mysqli_query() instead. Following is the code example utilizing mysqli class. This is procedural way but you can use it in OOP style as well.

    //Connect to database
    $host = "localhost"; //Change according to yours
    $username = "root"; //Change according to yours
    $password = ""; //Change according to yours
    $database = "test"; //Change according to yours
    
    $con = mysqli_connect($host,$username,$password,$database); //Create the connection
    if(!$con)
    {
        echo "Not connected";
    }
    else
    {
        echo "Connected<br />";
    }
    
    //Prepare the query to fetch the database records
    $query = "select * from TableName"; //Replace the table name with yours
    $sql = mysqli_query($con,$query); //Execute the query
    while($result = mysqli_fetch_assoc($sql)) //Loop through, till there are records corresponding to the query
    {
        $rows[] = $result; //Store all the records in an array
    }
    
    //Now iterate over each property using foreach loop
    foreach($rows as $row)
      {
          echo "Name - ".$row['name']." Age - ".$row['age']."<br />";
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址