我试图使用Mysqli代替Mysql与php,以便从我的数据库收集内容,下面的代码(代码1)工作正常,但我有2个问题:
1 - 代码1显示同一行上的所有行,而不是彼此之上的所有行。
2 - 我无法获得如何获取表的列名,就像我使用mysql方法(代码2)时那样。
--------------------- code 1 ----------------
double kinetic_energy(double mass, std::array<double,3> const&velocity)
{
return 0.5 * mass * (square(velocity[0])+square(velocity[1])+square(velocity[2]));
}
---------------- code 2 ------------
<?php
$db = new mysqli('localhost', 'root', '', '...');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL SELECT * FROM `...`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo "<tr class='info'>
<td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
</tr>"; } ?>
------------修正更新------------------
addedd
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('dhocp');
$query = "SELECT * FROM ...";
$result = mysql_query($query);
echo "<table class='table'>";
echo '<tr>';
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo "<th>".mysql_field_name($result, $i)."</th>";
}
echo '</tr>';
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr class='info'><td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
</tr>";
}
echo "</table>";
mysql_close();
?>
在while循环之前的代码1中
------------修复更新2 --------------显示列表----
echo "<table class='table'>";
答案 0 :(得分:3)
你可以,例如在第一次迭代中打印数组键(=字段名称)
$header = true;
foreach( $mysqli->query('SELECT id,x,y FROM soFoo') as $row ) {
if ( $header ) {
// on the first iteration print the array-keys <-> field names
$header = false;
echo '<tr><th>', join('</th><th>', array_map('htmlspecialchars', array_keys($row))), '</th></tr>', "\r\n";
}
echo '<tr><td>', join('</td><td>', array_map('htmlspecialchars', $row)), '</th></tr>', "\r\n";
}
或者您按照http://docs.php.net/mysqli.quickstart.metadata
的描述获取元数据$result = $mysqli->query('SELECT id,x,y FROM soFoo');
$meta = $result->fetch_fields();
echo '<tr><th>', join('</th><th>', array_map( function($e) { return htmlspecialchars($e->name); }, $meta)), '</th></tr>', "\r\n";
foreach( $result as $row ) {
echo '<tr><td>', join('</td><td>', array_map('htmlspecialchars', $row)), '</th></tr>', "\r\n";
}