简体   繁体   中英

How do I get different user selected SQL tables displayed as an html table using PHP?

I am creating a page that prompts for server login info, and redirects after submitting correct information. Once on the next page, there is a select form with different table names representing tables inside of the database. Once one is selected, and 'select table' is clicked, it is to display the entire table from the database as a table in html by using PHP. I'm not sure how to figure out the number of columns in a sql table to be able to display it using a loop and html table tags.

<?
session_start();
if(!isset($_SESSION['session']))
{
    $_SESSION['session'] = 0;
}
if(isset($_POST['host']))
{
    $_SESSION['host'] = $_POST['host'];
    $_SESSION['dbname'] = $_POST['dbname'];
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['pw'] = $_POST['pw'];
}

?>
<!DOCTYPE html>
<html>

<body>
    <?          
    if(isset($_POST['logout']))
    {
        $_SESSION['session'] = 0;
    }

    if(isset($_POST['submit']))
    {
        try
        {
            $db = new PDO("mysql:host=".$_POST['host'].";dbname=".$_POST['dbname'], $_POST['username'], $_POST['pw']);
        }
        catch(Exception $error)
        {
            die("Connection to user database failed: " . $error->getMessage());
        }

        try
        {
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
            $query = "SHOW TABLES";
            $results = $db->query($query)->fetchall();
            $_SESSION['session']=1;
        }
        catch(Exception $error)
        {
            echo "Problem with ~query, go back to home screen";
            $_SESSION['session']=0;
        }
    }       

    if($_SESSION['session'] == 0)
    {?>
    <form action="<?$_SERVER['PHP_SELF']?>" method="post" name='initialentry'>
        <table border='0' style='text-align: center'>
            <tr>
                <td style='text-align: right;'>Enter host name:</td>
                <td style='text-align: left;'>
                    <input type='text' name='host' value='localhost'>
                </td>
            </tr>
            <tr>
                <td style='text-align: right;'>Enter database name:</td>
                <td style='text-align: left;'>
                    <input type='text' name='dbname' value='zxyx999'>
                </td>
            </tr>
            <tr>
                <td style='text-align: right;'>Enter user name:</td>
                <td style='text-align: left;'>
                    <input type='text' name='username' value='zxyx999'>
                </td>
            </tr>
            <tr>
                <td style='text-align: right;'>Enter password:</td>
                <td style='text-align: left;'>
                    <input type='password' name='pw' width='15' value='12345'>
                </td>
            </tr>
            <tr>
                <td style='text-align: right;'>
                    <input type="reset" value="Reset">
                </td>
                <td style='text-align: left;'>
                    <input name='submit' type="submit" value="Submit">
                </td>
            </tr>
        </table>
    </form>
    <?}

    if($_SESSION['session']==1)
    {
        ?><form action='<?$_SERVER['PHP_SELF']?>' method='post' name='tableList'>
        <select name='selected'><?
            foreach($results as $row)
            {
                echo "<option value=".$row[0].">" . $row[0] . "</option>";
            }?>
        </select>
        <input type="submit" name="selectTable" value="Select Table">
        <input type="submit" name="logout" value="logout">
        </form><?
    }

    if(isset($_POST['selectTable']))
    {
        try
        {
            $db = new PDO("mysql:host=".$_SESSION['host'].";dbname=".$_SESSION['dbname'], $_SESSION['username'], $_SESSION['pw']);
        }
        catch(Exception $error)
        {
            die("Connection to user database failed: " . $error->getMessage());
        }

        try
        {
            $statement = $db->prepare("SELECT * FROM ".$_POST['selected']);
            $statement->execute();
        }
        catch(Exception $error)
        {
            echo "Problem with ~query";
        }

        echo "</br>";
        echo "<table border= '1'>";

        while($row = $statement->fetch())
        {
            echo $row['book_id'] . $row['title'];
        }

        echo "</table>";
    }

    ?>
</body>
</html>

You can use columncount property of the PDOStatement object after execute() has been called to determine the number of columns in the resultset.

Update: let's see some code

...
$c=$statement->columnCount()-1; //column indexes in resultset are 0 based
while($row = $statement->fetch())
    {
        echo '<tr>'; //start row
        for($i=0; $i<=$c; $i++)
            {
                echo '<td>'.$row[$i] . '</td>'; //print cell
            }
        echo '</tr>'; //close the row
    }
...

To select the number of the columns of a table you can use this query.

SELECT COUNT(*) AS total_columns
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'selected_table' AND table_schema = 'your_database';

You can find more info about INFORMATION_SCHEMA here .

you'd want to use the INFORMATION_SCHEMA.COLUMNS table as indicated in this answer

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' 
    AND `TABLE_NAME`='yourtablename';

you first create a loop where you make the <tr><th>[CONTENT]</th>...</tr> row of the table then you run your existing loop to generate the <tr><td>[CONTENT]</td>...</tr> rows.

your first loop would more or less be the same as your second with the difference being that you are using a different sql result, using <th> instead of <td> and a loop inside your second loop. this will...

display the entire table from the database as a table in html

and if you need a row/column count you can stick some sort of iterator in each loop

first loop example

echo "<tr>";
$countColumn = 0;
while($row = $statement->fetch())
{
    echo "<th>".$row['COLUMN_NAME']."</th>";
    $countColumn += 1;
}
echo "</tr>";

second loop example

$countRow = 0;
while($row = $statement->fetch())
{
    echo "<tr>";
    foreach($row as $data)
    {
        echo "<td>".$data."</td>";
        $countRow += 1;
    }
    echo "</tr>";
}

NOTE: Browsers are retarded children, unless in your

echo "<table border= '1'>";

while($row = $statement->fetch())
{
    echo $row['book_id'] . $row['title'];
}

echo "</table>";

part your $row['book_id'] . $row['title'] $row['book_id'] . $row['title'] has your <tr><td> tags don't let them fill in the blanks in. especially if this is going to be a non-intranet page

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM