PHP / MySQL resultset'de ile birlikte sütun adlarını almak nasıl?

3 Cevap php

Tamam mı?

$i = 0;
while ($row = mysql_fetch_array($result))
{
    $resultset[] = $row;
    $columns[] = mysql_fetch_field($result, $i);
}

Sonra baskı çalışırken

<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr>

Ben bir hata var

Catchable fatal error: Object of class stdClass could not be converted to string

3 Cevap

mysql_fetch_field fonksiyonu deneyin.

Örneğin:

<?php
$dbLink = mysql_connect('localhost', 'usr', 'pwd');
mysql_select_db('test', $dbLink);

$sql = "SELECT * FROM cartable";
$result = mysql_query($sql) or die(mysql_error());

// Print the column names as the headers of a table
echo "<table><tr>";
for($i = 0; $i < mysql_num_fields($result); $i++) {
    $field_info = mysql_fetch_field($result, $i);
    echo "<th>{$field_info->name}</th>";
}

// Print the data
while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    foreach($row as $_column) {
        echo "<td>{$_column}</td>";
    }
    echo "</tr>";
}

echo "</table>";
?>

mysql_fetch_assoc sadece bir ilişkisel dizi almak ve ilk yineleme ile sütun adlarını almak için kullanın:

$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
    if (empty($columns)) {
        $columns = array_keys($row);
    }
    $resultset[] = $row;
}

Şimdi ilk yineleme ile tablonun baş yazdırabilirsiniz de yapabilirsiniz:

echo '<table>';
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
    if (empty($columns)) {
        $columns = array_keys($row);
        echo '<tr><th>'.implode('</th><th>', $columns).'</th></tr>';
    }
    $resultset[] = $row;
    echo '<tr><td>'.implode('</td><td>', $rows).'</td></tr>';
}
echo '</table>';

Sen bakmak istiyorum

 mysql_fetch_assoc

Ilişkilendirilebilir tuşunun tuş sütun adıdır => değer çifti olarak her satır verir.

Belgeler here