PHP 未定义索引 - sortby

Ada*_*olt 1 php mysql

它基本上显示来自 mysql 数据库的数据并使用

\n\n
$sortby = $_GET[\'sort\'];\n
Run Code Online (Sandbox Code Playgroud)\n\n

我得到的错误是

\n\n
Notice: Undefined index: sort in /home/4507408/public_html/list.php on line 8\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是完整的代码,有什么想法吗?(第 8 行是 $sortby = $_GET[\'sort\'];)

\n\n

感谢您的浏览:)

\n\n
<?php\n$dbhost = \'localhost\';\n$dbuser = \'CU4507408\';\n$dbpass = \'adamadam1\';\n$dbname = \'CU4507408\';\n$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to        database");\nmysql_select_db($dbname);\n$sortby = $_GET[\'sort\'];\n?>\n
Run Code Online (Sandbox Code Playgroud)\n\n

那是在页面的顶部

\n\n
<table border="1">\n\n    <tr>\n        <th><a href="list.php?sort=name">Product Name:</a></th>\n        <th><a href="list.php?sort=price">Price \xc2\xa3</a></th>\n        <th><a href="list.php?sort=manufacturer">Manufacturer</a></th>\n        <th><a href="list.php?sort=rating">Rating</a></th>\n        <th><a href="list.php?sort=categoryname">Category</a></th>\n    </tr>\n    <?php\n    $query = "SELECT p.productID, p.name, p.price, p.manufacturer, p.rating, c.categoryname FROM product p INNER JOIN category c WHERE p.categoryID=c.categoryID ORDER BY $sortby ASC;";\n    $result = mysql_query($query) or die("failed!");\n    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {\n        ?>\n        <tr>\n\n            <td><a href="link.php?productID=<?= $row[\'productID\'] ?>"><?= $row[\'name\'] ?></a></td>\n            <td><?= $row[\'price\'] ?></td>\n            <td><?= $row[\'manufacturer\'] ?></td>\n            <td><?= $row[\'rating\'] ?></td>\n            <td><?= $row[\'categoryname\'] ?></td>\n        </tr>\n<? } ?>\n
Run Code Online (Sandbox Code Playgroud)\n

hsz*_*hsz 5

只需尝试:

$sortby = isset($_GET['sort']) ? $_GET['sort'] : 'default_value';
Run Code Online (Sandbox Code Playgroud)

另外,如果您使用传递的 valriables,则$_GET必须检查它是否不是在查询中注入某些内容的值。好的做法是:

$sortbyValues = array('price', 'manufacturer', 'rating', 'categoryname');
$sortby = isset($_GET['sort']) && in_array($sortby, $sortbyValues) ? $_GET['sort'] : 'default_value';
Run Code Online (Sandbox Code Playgroud)