Have not programmed in over 20 years. I am trying to use PHP to dynamically create Check Boxes by getting Column Names from my database Table (Fruit). Have researched hundreds of postings for examples unsuccessfully. Overview of what I am doing:
Step A: (1) Using PHP, Get the NAME for each column (Field) for the table (Fruit) in my database. (2) For each column (field) name, dynamically create a Checkbox with the column name beside it in a Website form viewable by members. (3) CSS formatting to be created in later coding efforts. (4) This PHP code with a change to Table name, will be reused numerous times to do the same function for several other web pages (i.e. tables – vegetables, melons, etc….)
Step B: (1) Members will select (click on) from 1 to all checkboxes generated in Step A. (2) Members will then select (click on) SUBMIT causing each selected checkbox item to be written into a new row (record), appearing in the correct Column in the table (Fruit).
Step C: (1) Members will be able to Search database to see what FRUIT items other members have posted in the table (Fruit). (2) Search feature to be incorporated in a later coding effort for web site.
Below Code sort of works, but fails to meet goal because each Table would require knowing number of columns, coding page for the number of columns, and if table changes have to mod the code for that page.
<?php
$link = mysql_connect('localhost', 'myneighborhood01', 'Tsc-100');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
echo "Connected to Data Base successfully <br>";
$dbname = 'mydatabase';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);
echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 1);
echo mysql_field_name($res, 2);
echo mysql_field_name($res, 3);
echo mysql_field_name($res, 4);
echo mysql_field_name($res, 5);
echo mysql_field_name($res, 6);
?>
The following code is closer to what I am trying to do.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM table_name ";
$result = $conn->query($sql);
if ($result->num_columns > 0) {
// output data of each column
while($column = $result->fetch_assoc()) {
echo "" . $column[]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>