I am new to PHP.
Please I need help with the code below.I am trying to use PHP switch statement to display table data from MySQL database based on the selection of a particular table. I have 2 PHP files (index.php and table_data.php). The file index.php has a function that list all the tables from the database with onclick function to list the row and columns of a particular table. The second file table_data.php contains the switch statement but the switch statement does not list the table data when a particular table is selected, it does not list the row and columns of the table. I Think the problem is with the switch statement. Please help and thanks in advance. below is the table_data.php file
<?php
include_once 'connect.php';
function showtable()
{
$dbname = 'Database';
echo "TABLE NAMES";
$tables = mysql_query("SHOW TABLES FROM `" . $dbname . "`");
while (list($table) = mysql_fetch_row($tables))
{
echo "<div onclick='table()' title='click to show table data'>$table</div>";
}
}
?>
<body>
<script>
function table()
{
document.getElementById('video').src='table_data.php';
}
</script>
<table width="100%" cellpadding="1" id="content">
<tr>
<td width="20%" valign="top" bgcolor="#0033FF">
<?php showtable();?>
</td>
<td valign="top" >
<iframe id="video" src="table_data.php">
</iframe>
</td>
</tr>
</table>
</div>
</body></html>
It's probably because the variable $table
is not visible inside the function showtabledata()
. So you can either import (sort of) the variable inside the function like this :
$table = '';
function showtabledata()
{
/* other code */
global $table;
/* other code */
}
or can pass the variable as an argument to the function like showtabledata($table)
as suggested by Sean, like this :
$table = '';
function showtabledata($table)
{
// use $table
}
Have a look at Language variables scope
Please try with this code, use showtabledata($table) , pass $table through function
<?php
include_once 'connect.php';
$table = '';
function showtabledata($table)
{
$result = mysql_query("SELECT * FROM ".$table);
if (!$result)
{
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<div class='sidemenu'>Table: {$table}</div>";
echo "<table><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
}
switch($table)
{
case '1':
$table = 'table1';
echo "table not available";
break;
case '2':
$table = 'table2';
showtabledata($table);
break;
case '3':
$table = 'table3';
showtabledata($table);
break;
case '4':
default:
$table = 'table4';
showtabledata($table);
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.