如何从Mysql表中读取数据?

时间:2012-10-16 05:20:20

标签: mysql

我遇到同样的问题,从mysql读取数据并将其存储在数组中。 我有这样的表

id     engineering     science      language
_____________________________________________

1      chemical        bio           english
2      electrical      chemistry     malay 
3      mechanical      astronomy     spanish 

如何从工程中读取所有数据并将其存储在数组中?我可以在PHP中进行任何散列,或者关联数组已经包含此散列函数。 请帮忙。

1 个答案:

答案 0 :(得分:0)

使用MySQLi的准系统示例:

// connect to your database
$mysqli = new mysqli("hostname", "username", "password", "database");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// setup your query
$query = "SELECT * FROM engineering ";
$results = array();
// execute your query
if ($result = $mysqli->query($query)) {
    // the query was successful; iterate through each result fetching an
    // associative array and add it to the `$results` list
    while ($row = $result->fetch_assoc()) {
        $results[] = $row;
    }
    $result->free();
}
$mysqli->close();

// process all results in `$results` array! (simple output)
foreach ($results as $result) {
    echo $result['id'] . ' ' . $result['engineering'] . '<br />';
}