Jump to content

create html check box from mysql on the fly


goodgeneguo

Recommended Posts

Hello all, here is what I am trying to do:  on my php page I want do a search against certain mysql table.  Once the results are retrieved, I will load a function called 'checkbox'.  This function will have paramenters of database name and table name of mysql database.  Based on the parameters, the function would generate some checkboxes that have the names of the table fields.  The idea is that user can select certain fields and then generate an EXCEL report based on the field selected.  Here is my function 'checkbox'.  My problem is that when the function is executed, the generated checkboxes do not have names corresponding to table's field names, instead give me output like "mysql_field_name(Resource id #25, 0) " etc.  I used "echo $result" and also got an output " results are Resource id #25 ".
Here is the codes of my function.  What could have gone wrong?  Thanks in advance.

// This is a function that will open a database and table, then generate checkbox for each field or let user to select all, output as html code, then close database connection
  function checkbox($db, $table){
$hostname="localhost";
  $mysql_login="test";
  $mysql_password="test";
  $link = mysql_connect($hostname, $mysql_login , $mysql_password);
 
  if (!$link )
  {
    echo "Can't connect to mysql."; 
  }else{
    if (!(mysql_select_db("$db",$link)))
{
    echo "Can't connect to db.";
  }
  }
$result = mysql_query("select * from $table", $link);
echo "results are $result <br> ";  // here i got an output of " results are Resource id #25 "
$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++){
  echo " <input type='checkbox' value=$i name='cbx'. $i> mysql_field_name($result, $i) <br>";
echo " mysql_field_name($result, $i) <br>";
}



mysql_close($link);

  } 
When you run [b]$result = mysql_query("select * from $table", $link);[/b] $result is a pointer to the actual query results, not the results themselves. You need to pull the records from the results using the pointer like this:

[code]<?php
  if (!mysql_num_rows($result)) { echo "There were no records"; }
  else {
    echo "<table border=1>";
    $firstRecord = false;
    while ($row = mysql_fetch_assoc($result)) {
      if ($firstRecord) {
        echo "<tr>";
        foreach ($row as $key => $value) {echo "<td>".$key."</td>";}
        echo "</tr>"; $firstrecord = false;
      }
      echo "<tr>";
      foreach ($row as $value) { echo "<td>".$value."</td>"; }
      echo "</tr>";
    }
    echo "</table><br>";
  }
?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.