How to get the columns names along with resultset in php/mysql? - php

Is this OK ?
$i = 0;
while ($row = mysql_fetch_array($result))
{
$resultset[] = $row;
$columns[] = mysql_fetch_field($result, $i);
}
Then when trying to print
<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr>
I got an error
Catchable fatal error: Object of class stdClass could not be converted to string

Try the mysql_fetch_field function.
For example:
<?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>";
?>

Use mysql_fetch_assoc to get only an associative array and retrieve the column names with the first iteration:
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
}
$resultset[] = $row;
}
Now you can print the head of your table with the first iteration as well:
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>';

You want to look at
mysql_fetch_assoc
Which gives each row as an associative key => value pair where the key is the column name.
Documentation here

Here is a more modern solution with ...i:
$db_link = #mysqli_connect($server, $user, $pass, $db) or die("Connection failed");
$spalten = ['pc_name', 'pc_type', 'pc_snr', 'pc_bj', 'mo_port_1', 'mo_snr_1', 'mo_bj_1', 'mo_port_2', 'mo_snr_2', 'mo_bj_2'];
$abfrage = "SELECT " . implode(',', $spalten) . " FROM hardware order by pc_name";
$liste = mysqli_query($db_link, $abfrage);
$spalten = mysqli_num_fields($liste);
while ($werte[] = mysqli_fetch_array($liste, MYSQLI_ASSOC)) {}
<table class="display" id="table" style="width:100%">
<thead>
<tr>
<?php
for ($i = 0; $i < $spalten; $i++) {
$feldname[$i] = mysqli_fetch_field_direct($liste, $i)->name;
echo '<th>' . ucfirst($feldname[$i]) . '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < mysqli_num_rows($liste); $i++) {
?>
<tr>
<?php for ($j = 0; $j < $spalten; $j++) {
?>
<td><?php
echo $werte[$i][$feldname[$j]];
?>
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>

Though it's deprecated and no longer in PHP 7 you can avoid having to use an object by using the function mysql_field_name instead which returns a string.

Related

SQL loop won't print column names

I have several columns in my database and I would like to print out all the column names, i.e. the names of the people in the database.
I'm having trouble with selecting ONLY the column names, this piece of code will run the loop but only the $i will print, not the actual names of the columns. Any advice? Thanks
$query = mysql_query("SELECT * FROM People");
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$name = $row['query'];
if ($count > '1') {
?>
<table>
<tr>
<td><p><b><?php print( $name . "</p></td></tr>");
$i = $i + 1;
?>
P.s.
I tried with:
select COLUMN_NAME from Names.COLUMNS where TABLE_NAME = 'Names' but this won't work either, it tells me: access denied, don't really know why
Here is the code to get column names for your table.
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
But, as you get access denied. It means you do not have privilege to access table metadata.
So you can use either,
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
// Here $columns is array and it contains all column name
}
}
I think you should try this:
$query = "SELECT * FROM People";
$result = mysqli_query( $conn, $query );?>
<table>
<?php
while($row = mysqlsi_fetch_assoc( $result ) ){
?>
<tr>
<td><p><?php print( $row->id );?></p></td>
<td><p><?php print( $row->name );?></p></td>
<td><p><?php print( $row->lastname );?></p></td>
</tr>
<?php
} ?>
</table>
Assuming,your SQL table has these fields: id, name, lastname.
Inside your while loop you could use
foreach($row as $column => $value){
printf("Column: %s has value: %s\n", $column, $value);
}
As mysql_fetch_assoc returns an associative array so you want the key => value information.
HTH
Use mysql_field_name function in php to get column name
$query = mysql_query("SELECT * FROM People");
$i = 1; $j=0; // I have declared $j incrementor
while($row = mysql_fetch_assoc($query)) {
$name = $row['query'];
$columnname = mysql_field_name($query, $j); // This gives the column name of table.
if ($count > '1') {
?>
<table>
<tr>
<td><?php echo $columnname; ?></td>
<td><p><b><?php print( $name . "</p></td></tr>");
$i = $i + 1;
$j = $j + 1;
?>

Displaying data horizontally using php and mysql

Hi I'm attempting to display data retrieved from a mysql table horizontally in an html table using php. The code below works well except for the fact that it leaves out the first record (starts at the second record) in my database. I'm sure it has something to do with the counter but I can't seem to figure out how to get it to stop doing this. If anyone can point out my error I'd really appreciate it!
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
$i = 0;
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
if ($i==0) {
echo "<tr>\n";
}
echo "\t<td align=\center\">$first_name</td>\n";
$i++;
if ($i == $items) {
echo "</tr>\n";
$i = 0;
}
}//end while loop
if ($i > 0) {
for (;$i < $items; $i++) {
echo "<td> </td>\n";
}
echo '</tr>';
}//end ($i>0) if
echo '</table>';
}else {
echo 'no records found';
}
try and remove the 1st
$row = mysql_fetch_array($result);
you are calling it twice, that's why it skips 1 row in your while loop
try this simpler.
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
echo "<tr>";
for ($i=0 ; $i <= $items ;$i++) {
echo "<td align='center'>".$first_name."</td>";
}
}//end while loop
echo "</tr>";
echo '</table>';
}else{ echo 'no records found'; }
I have run into this issue before. Try the do while loop instead. Example
do {
// code
} while($row = mysql_fetch_array($result)); //end while loop
$row = mysql_fetch_array($result);
1) remove this line of code from ur scripts
2) only use while loop code instead.

Displaying all tables in a database

How do I display out all the information in a database (All tables and records) using PHP? I read displaying tables as HTML table but how do I do it for all the tables?
I tried the example here:
http://davidwalsh.name/html-mysql-php
But it shows the table names, how do I also display all the values?
Okay got it .. try this
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "username", "password", "DB");
$result = $mysqli->query("SHOW TABLES");
while ($row = $result->fetch_row()) {
$table = $row[0];
echo '<h3>', $table, '</h3>';
$result1 = $mysqli->query("SELECT * FROM `$table`");
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
$column = $mysqli->query("SHOW COLUMNS FROM `$table`");
echo '<tr>';
while ($row3 = $column->fetch_row()) {
echo '<th>' . $row3[0] . '</th>';
}
echo '</tr>';
while ($row2 = $result1->fetch_row()) {
echo '<tr>';
foreach ($row2 as $key => $value) {
echo '<td>', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
$mysqli->close();
you can use the recursive function to display the tree Structure of your database.
Here is the a sample code from http://webcodingeasy.com/PHP/Simple-recursive-function-to-print-out-database-tree-structure
<?php
function print_menu($id = 0)
{
// get all records from database whose parent is $id
$result = $query->select_result("*", "table", "where parent = '".$id."'");
//check if there are any results
if($result != 0)
{
echo "<ul> n";
while($row = $query->fetch($result))
{
//print result and call function to check if it has children
echo "<li>".$row['name']."</li> n";
print_menu($row['ID']);
}
echo "</ul> n";
}
}
print_menu();
?>
If you want to pull all tables with the values in mysql, you can use the following code:
<?php
mysql_connect ("localhost", "DB_USER", "DB_PASSWORD"); //your mysql connection
mysql_select_db('DB_NAME') or die( "Unable to select database"); //your db name
$tables = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema='DB_NAME'"); //pull tables from theh databsase
while ($table= mysql_fetch_row($tables)) {
$rsFields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($field = mysql_fetch_assoc($rsFields)) {
echo $table[0].".".$field["Field"].", "; //prints out all columns
}
echo $table[0];
$query = "SELECT * FROM ".$table[0]; //prints out tables name
$result = mysql_query($query);
PullValues($result); //call function to get all values
}
//function to pull all values from tables
function PullValues($result)
{
if($result == 0)
{
echo "<b>Error ".mysql_errno().": ".mysql_error()."</b>";
}
elseif (#mysql_num_rows($result) == 0)
{
echo("<b>Query completed. No results returned.</b><br>");
}
else
{
echo "<table border='1'>
<thead>
<tr><th>[Num]</th>";
for($i = 0;$i < mysql_num_fields($result);$i++)
{
echo "<th>" . $i . " - " . mysql_field_name($result, $i) . "</th>";
}
echo " </tr>
</thead>
<tbody>";
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
echo "<tr><td>[$i]</td>";
$row = mysql_fetch_row($result);
for($j = 0;$j < mysql_num_fields($result);$j++)
{
echo("<td>" . $row[$j] . "</td>");
}
echo "</tr>";
}
echo "</tbody>
</table>";
} //end else
}
?>
I am using this and works fine in mysql, for mysqli you need to tweak it a very little.

how do I traverse rows in a table

I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}

How to increase mysql_fetch_array pointer?

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$row = mysql_fetch_array($result, MYSQL_ASSOC) //it's not increase ?
}
i want increase two time in each loop?
for
<table>
<td>**1 times**</td><td>**1 times**</td>
</table>
I think the documentation is very clear. http://hu.php.net/manual/en/function.mysql-fetch-array.php or http://hu.php.net/manual/en/function.mysql-fetch-assoc.php.
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
You don't need that.
If you want to print your data formatted in 2 columns, select it all into array and then use that array for the formatted output.
one of possible solutions
<?php
//collect data into array
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
//and here goes template part
?>
<html>
<? $data = array_chunk($data, 2) ?>
<table>
<? foreach ($data as $chunk): ?>
<tr>
<? foreach ($chunk as $row): ?>
<td><?=$row['name']?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
it WILL increase the pointer by 1 step...
therefore:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// logic here
}
will perform the loop and logic
Why not do something like this:
$max_row = 100;//mysql_num_rows($result);
for($idx = 0; $idx < $max_row; $idx+=2){
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
//do what you want to do here...
}
if you have 10 records, it will echo row 0, 2, 4, 6, 8.
<?php
$counter=0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if ($counter % 2)
{
echo '<table><tr>'; // start table
}
echo '<td>' . $row['foo'] . '</td>'; // echo result
if (!$counter % 2)
{
echo "</tr></table>"; // end table
}
$counter++;
}
?>
Maybe you want mysql_data_seek?

Categories