-1

ドロップダウン リストがあるインターフェイスがあります。項目を選択し、[送信] ボタンをクリックして mysql でデータベースを表示する必要がありますが、機能しません。「テーブル 'balhaf.$table' が存在しません」というエラーが表示されます

これが私のコードです

<html>
<body>

<form method="post" action="list_files.php">
<input name="go" type="submit" value="submit" / >

<?php
$dbname = 'balhaf';

if (!mysql_connect('localhost', 'sqldata', 'sqldata')) {
echo 'Could not connect to mysql';
exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

echo '<select name="dropdown" style="width:150px">';

echo '<option value="">Select</option>';

while ($row = mysql_fetch_row($result)) {

echo '<option value="'.$row[0].'">'.$row[0].'</option>';

}

echo '</select>';
echo '</form>';
mysql_free_result($result);

?>
</body>
</html>

私の2番目のコード「list_files.php」

<?php

if(isset($_POST["dropdown"]))

{
echo "ok";
}

$table = $_POST['dropdown'];
// Connect to the database
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Query for a list of all existing files
$sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM $table';
$result = $dbLink->query($sql);

// Check if it was successfull
if($result) {
// Make sure there are some files in there
if($result->num_rows == 0) {
    echo '<p>There are no files in the database</p>';
}
else {
    // Print the top of a table
    echo '<table border="1" align="center">
          <H2 align="center"> Report Table</H>
            <tr>
                <td><b>Name</b></td>
                <td><b>Mime</b></td>
                <td><b>Size (bytes)</b></td>
                <td><b>Created</b></td>
                <td><b>Download</b></td>

            </tr>';
 // Print each file
    while($row = $result->fetch_assoc()) {
        echo "
            <tr>
                <td>{$row['name']}</td>
                <td>{$row['mime']}</td>
                <td>{$row['size']}</td>
                <td>{$row['created']}</td>
                <td><a style='text-decoration:none;' href='get_file.php?id=    {$row['id']}'>Download</a></td>
            </tr>";
    }

    // Close table
    echo '</table>';
   }

   // Free the result
   $result->free();
   }
   else
   {
   echo 'Error! SQL query failed:';
   echo "<pre>{$dbLink->error}</pre>";
   }

  // Close the mysql connection
  $dbLink->close();
  ?>
4

3 に答える 3

0

変数が文字列内にある場合は、変数を {} で囲みます。

 $sql = "SHOW TABLES FROM $dbname"; //might work
 $sql = "SHOW TABLES FROM {$dbname}"; //preferable

文字列内に変数を入れるときは、必ず二重引用符を使用してください。

 $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM $table'; //wrong
 $sql = "SELECT `id`, `name`, `mime`, `size`, `created` FROM {$table}"; //right

また、文字列内に配置する変数をユーザーに設定させると、SQL インジェクション攻撃を受ける可能性があることに注意してください。

于 2013-08-21T23:52:58.523 に答える