问题
So I have this code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include "../includes/db_conn.php";
$data = $_POST['tabledb'];
$sfm = $dbm->prepare('SELECT * FROM '.$data.'');
$sfm->execute();
$all = $sfm->fetchAll();
?>
<!DOCTYPE html>
<html>
<body>
<?php
foreach ($all as $row)
{
echo "<option value=\"info\">" . $row[0] . "</option>";
}
?>
</body>
</html>
oke a littel context if have a dropdown menu where you can select rows from the database, if you select a table that table is send to this page trough a ajax call. that is why I have:
$data = $_POST['tabledb'];
in my code. now I would like to show the contents of the tables, but every table has a different amount of columus and colum names. how do I show the contents of the tables without specifying the colum name? please help.
EDIT
what I tried, I tried making it a for loop, didn't work.
EDIT 2
I wasn't clear enough, I am trying to get the same result as print_r but with a echo.
回答1:
You could use implode to combine all elements for each row into a single string:
foreach ($all as $row)
{
echo ‘<option value="info">’ . implode(‘|’, $row) . ‘</option>‘;
}
Or you could use use nested foreach:
回答2:
If you are using the fetchAll function, it return all data inform of index and associative array.
If you want to get the data only with column name, need to use like below:
$all = $sfm->fetchAll(\PDO::FETCH_ASSOC);
回答3:
Perhaps try this, if you just want to list the columns per table:
foreach($row[0] as $column => $value){
echo "<option value=\"info\">" . $column . "</option>";
}
This is assuming that each table has data.
回答4:
I think a simple way to do this would be to do something like:
$columns = array_keys($result[0]);//this will give you an array of all the columns
foreach($columns as $col) {
echo <td>col</td>
}
then do the values
foreach($result as $row) {
echo <td>row['value1']</td>
echo <td>row['value2']</td>
}//or do another loop in here to through the whole array
then you can display it in a table format which will match what you have in your db
and for your drop down you can reuse the columns array
$columns = array_keys($result[0]);//this will give you an array of all the columns
foreach($columns as $col) {
echo <option value = '.$col.'>col</option>
}
来源:https://stackoverflow.com/questions/54982844/sql-show-data-in-tables-without-specifying-the-colum-name