如何使用 php 和 mysql 从查询创建 table

How to create a table from a query using php and mysql

我正在尝试创建一个文件,该文件将从查询中删除并重新创建 table。 我不断收到语法错误。自从我在 mysql 工作以来已经有一段时间了,但我没有看到错误。再来一双眼睛就好了!

$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );  

//drop table for updated database
//Create query
$q = "
DROP TABLE IF EXISTS dbName.tbName;
CREATE TABLE  dbName.tbName (ID int) AS 'SELECT
dbName.tbName.ID
FROM
dbName.tbName
ORDER BY
dbName.tbName.count DESC
LIMIT 8'";
;

//run query
$r = @mysqli_query ($dbc, $q);


//Displays resutls if query ran correctly
if ($r) { // If it ran OK, display the records.

        // Table header.
        echo '<table align="center" >
        <tr><td align="left"><b>Number 1</b></td><td align="left"><b>Number 2</b></td><td align="left"><b>Number 3</b></td><td align="left"><b>Number 4</b></td><td align="left"><b>Number 5</b></td><td align="left"><b>Number 6</b></td>
        <td align="left"><b>Number 7</b></td><td align="left"><b>Number 8</b></td><td align="left"><b>Number 9</b></td><td align="left"><b>Number 10</b></tr>';

        // Fetch and print all the records:
        while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
                echo '<tr><td align="left">' . $row['Number_1'] . '</td><td align="left">' . $row['Number_2'] . '</td><td align="left">' . $row['Number_3'] . '</td><td align="left">' . $row['Number_4'] . '</td><td align="left">' .
                $row['Number_5'] . '</td><td align="left">' . $row['Number_6'] . '</td><td align="left">' . $row['Number_7'] . '</td><td align="left">' . $row['Number_8'] . '</td>
                <td align="left">' . $row['Number_9'] . '</td><td align="left">' . $row['Number_10'] . '</td></tr>'."\n";
        }

        echo '</table>'; // Close the table.

        mysqli_free_result ($r); // Free up the resources.      

} else { // If it did not run OK.

        // Public message:
        echo '<p class="error">Your numbers could not be retrieved. We apologize for any inconvenience.</p>';

        // Debugging message:
        echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';

} // End of if ($r) IF.

mysqli_close($dbc); // Close the database connection.

我得到的错误是:

Your numbers could not be retrieved. We apologize for any inconvenience.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE dbName.tbName (ID int) AS 'SELECTdbName.tbNam' at line 2

Query: DROP TABLE IF EXISTS dbName.tbName;
CREATE TABLE dbName.tbName (ID int) AS 'SELECT
dbName.tbName.ID
FROM
dbName.tbName
ORDER BY
dbName.tbName.count DESC
LIMIT 8'

我认为这可能是构建 table.

时内部查询周围的单引号
$q = "
    DROP TABLE IF EXISTS dbName.tbName;
    CREATE TABLE  dbName.tbName (ID int) AS ( SELECT
    dbName.tbName.ID
    FROM
    dbName.tbName
    ORDER BY
    dbName.tbName.count DESC
    LIMIT 8 )";

"SELECT" 和 "dbName.tbName.ID" 之间缺少空格 space ?