PHP从数据库中获取数组项

时间:2015-10-30 18:43:44

标签: php mysql arrays

我试图从数据库中获取数组项。 香港专业教育学院试过这个远远的

$q1 = $sql->Query("SELECT * FROM `SYSTEM` WHERE `active`='1'");
$r1 = MySQL_fetch_Object($q1)
$randomheadline = array($r1->headline);

和$ r1->标题确实返回

"Something1", "Something2", "Something3", "Something4"

但是当我尝试回显数组时,它返回整个事物 这是我回应我的数组的方式

echo $randomheadline[2]; 

所以我的问题是如何将数据库中的所有数组项放入该数组?

1 个答案:

答案 0 :(得分:3)

我建议使用mysql_fetch_array或mysql_fetch_assoc。我已经包含了4个基本示例。希望你会发现其中一个有帮助。示例1和2可能符合您的最佳利益。运气最好!

    <?php
    $username = "root";
    $password = "testPASS";
    $dbname = "testDB";
    $hostname = "localhost"; 

    //Connectd to Database
    $conn = mysql_connect($hostname, $username, $password)
      or die("Unable to connect to MySQL");

    //Select Database
    $selected = mysql_select_db($dbname,$conn)
      or die("Could not select examples");

    //------------------------------ 
    //Example 1 - MYSQL_FETCH_ARRAY:
    //------------------------------
    $result = mysql_query("SELECT * FROM `SYSTEM` WHERE `active`='1'");
    $headline_array  = array();
    while($row = mysql_fetch_array($result)){
      $headline_array [] = $row['headline'];
    }
    echo $headline_array[0];

    //------------------------------    
    //Example 2 - MYSQL_FETCH_ASSOC:
    //------------------------------
    $result = mysql_query("SELECT * FROM `SYSTEM` WHERE `active`='1'");
    while( $row = mysql_fetch_assoc( $result)){
        $new_array[] = $row;
    }
    foreach($new_array as $array){
        echo $array['headline'];
    }

    //------------------------------
    //Example 3 - MYSQL_FETCH_ASSOC:
    //------------------------------
    $result = mysql_query("SELECT * FROM `SYSTEM` WHERE `active`='1'");
    while ($row = mysql_fetch_assoc($result)) {
    echo $row["headline"];
    echo $row[0];
    }

    //-------------------------------
    // Example 4 - MYSQL_FETCH_ARRAY
    //-------------------------------
    $result = mysql_query("SELECT * FROM `SYSTEM` WHERE `active`='1'");
    while ($row = mysql_fetch_array($result)) {
    echo $row['headline'];
    echo $row[0];
    }
?>