从php变量中选择SQL表

时间:2013-11-25 21:30:08

标签: php mysql sql

我从列表/数组中选择了一个随机表,我希望能够使用mysqli_query函数调用这个随机表,即动态选择一个表

这是我的代码:

<?php
            $mysqli=mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);

            // Check connection
            if (mysqli_connect_errno($mysqli))
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

            // Looks at all prodcuts and selects those that have special offers enabled
            // Selects a random table from the array
            $tables_special = ["ajbs_products_console" ,"ajbs_products_console_games", "ajbs_products_pc", "ajbs_products_pc_games", "ajbs_products_pc_parts"];
            $rtable = $tables_special[floor (rand(0,count($tables_special)-1))];
            echo "<p>".$rtable." was selected</p>";


            $products = mysqli_query("SELECT * FROM '".$rtable."'");


            echo "<p>".$products."</p>";
            while($productRow = mysqli_fetch_array($products))
            {
                if ($productRow['product_specials'] == 1)
                {
                    echo "<table>";
                    echo "<tr>";
                    echo "<td rowspan='2'><img src=" . $productRow['product_image'] . "/></td>";
                    echo "</tr>";
                    echo "<table border='1'>";
                    echo "<tr>";
                    echo "<td>Product Name</td>";
                    echo "<td>" . $productRow['product_name'] . "</td>";
                    echo "</tr>";
                    echo "<tr>";
                    echo "<td>Description</td>";
                    echo "<td>" . $productRow['product_description'] . "</td>";
                    echo "</tr>";
                    echo "</table>";
                }
            }

            mysqli_close($mysqli);
        ?>

我不知道为什么这不起作用

谢谢,

2 个答案:

答案 0 :(得分:3)

您不应该使用单引号引用表名,但使用反引号,单引号使其成为字符串而不是表名;

此外,mysqli_query函数需要一个额外的参数,即连接。

$products = mysqli_query("SELECT * FROM '".$rtable."'");

应该是;

$products = mysqli_query($mysqli, "SELECT * FROM `".$rtable."`");

答案 1 :(得分:0)

尝试

$products = mysqli_query($mysqli, "SELECT * FROM ".$rtable);