PHP单独如果其他声明

时间:2016-04-03 07:13:23

标签: php html mysql

<?php
    extract( $_GET );       
    $sql = "SELECT * FROM tablename order by Name DESC";
    $sql = "SELECT * FROM tablename where age = "31";
    $db = mysql_connect("localhost","root","password"); 
    if (!$db) {
    die("");
    }
    $db_select = mysql_select_db('databasename',$db);
    if (!$db_select) {
    die("");
    }
    if ( !( $result = mysql_query( $sql, $db ) ) ) {
    print( "Could not execute query! <br />" );
    die( mysql_error() . "</body></html>" );
    } // end if

    echo "<table>
    <tr>
    <th>Name</th>
    <th>Age</th>
    </tr>";

    while($row = mysql_fetch_array($result)){
        echo "<tr>";
        echo "<td>".$row['Name']."</td>";
        echo "<td>".$row['Age']."</td>";
    }
    echo "</table>";
    mysql_close( $db );
?>

当选择名称或年龄时,我应该在哪里添加运行sql语句的名称和年龄的if else语句?姓名和年龄来自不同的列,但在同一个表中

3 个答案:

答案 0 :(得分:1)

if(isset($_GET['age'])) {
    $sql = 'SELECT * FROM tablename where age = ' . $_GET['age'];
} else if(isset($_GET['name'])) {
    $sql = 'SELECT * FROM tablename order by Name DESC';
}

然后您可以将其用于以下网址:

  • www.example.com?age=31
  • www.example.com?name

请注意,这是一个非常简化的示例,您还需要验证输入。

编辑:您不应该使用mysql *(已弃用)函数,而是使用mysqli *或PDO。有关mysql *函数的更多信息,请阅读this question上发布的答案。

答案 1 :(得分:0)

看起来你需要检查$ _GET的键。

试试这个:

if (isset($_GET['Name']) && !empty($_GET['Name'])) {
     $sql = "SELECT * FROM tablename order by Name DESC";
} else if (isset($_GET['Age']) && !empty($_GET['Age'])) {
      $sql = "SELECT * FROM tablename where age = '".$_GET['Age']."'";
}

希望这有帮助。

答案 2 :(得分:0)

<?php
    error_reporting(-1);

    $db = mysqli_connect("localhost","root","password","databasename"); 
    if (!$db) { 
        die( mysql_error() . "</body></html>" );
    }

    if(isset($_GET['age'])) {
        // You can use the $_GET['age'] variable in the query if you want to, this makes you vulnerable to sql injection though. if you don't use prepared statements or escape it (read link below
        $sql = 'SELECT * FROM tablename where age = "31"';
    } else if(isset($_GET['name'])) {
        // Same as for age but $_GET['name'] in this case of course.
        $sql = 'SELECT * FROM tablename order by Name DESC';
    }

    $result = mysqli_query($sql, $db)
    if (!result ) {
        print( "Could not execute query! <br />" );
        die( mysql_error() . "</body></html>" );
    } // end if

    echo "<table>
    <tr>
    <th>Name</th>
    <th>Age</th>
    </tr>";

    while($row = mysqli_fetch_array($result)){
        echo "<tr>";
        echo "<td>".$row['Name']."</td>";
        echo "<td>".$row['Age']."</td>";
        echo "</tr>";
    }
    echo "</table>";
    mysqli_close($db);
?>

只要您不在查询本身中使用$ _GET变量,上面的查询就会保存,如果这是你想要的,你应该阅读准备好的语句:http://php.net/manual/en/mysqli.prepare.php