【问题标题】:Get result out of query [duplicate]从查询中获取结果[重复]
【发布时间】:2012-10-25 19:11:43
【问题描述】:

可能重复:
How do i “echo” a “Resource id #6” from a MySql response in PHP?

我正在寻找查询的结果,但它一直给我资源 ID #3。

以下是我的代码。

$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);

print_r($typeResult);

我在这里错过了什么步骤?

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您需要获取结果。您所做的只是发送查询。

    请注意,如果您正在编写新代码,则应使用 mysqli_PDO 函数,因为您的查询容易受到 SQL 注入攻击,而 mysql_ 函数是 being deprecated。犹豫了一下,下面是mysql_fetch_assoc 的示例。

    <?php
    
    $sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
    
    $result = mysql_query($sql);
    
    if (mysql_num_rows($result) == 0) {
        echo "No rows found, nothing to print so am exiting";
        exit;
    }
    
    // While a row of data exists, put that row in $row as an associative array
    // Note: If you're expecting just one row, no need to use a loop
    // Note: If you put extract($row); inside the following loop, you'll
    //       then create $userid, $fullname, and $userstatus
    while ($row = mysql_fetch_assoc($result)) {
        echo $row[sellingid];
    }
    
    mysql_free_result($result);
    
    ?>
    

    Reference

    【讨论】:

    • 感谢您的详细回复。我认为 php.net 是学习 mysqli 函数的最佳资源?
    • @wowzuzz 你可以使用 php.net 作为参考。 mysqli_PDO 函数有很多资源和教程。
    【解决方案2】:
    $type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
    $typeResult = mysql_query($type);
    $row = mysql_fetch_array($typeResult);
    print_r($row);
    

    【讨论】:

      【解决方案3】:

      更清晰的提示 - 使用 MySQLi 类/函数,请阅读:

      http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php

      或者如果你更喜欢 OOP 方法

      http://lt1.php.net/manual/en/mysqli-result.fetch-object.php

      【讨论】:

        【解决方案4】:

        您实际上并未获取查询结果。下面是两个使用 WHILE 循环将结果作为行获取的示例。然后,您可以获取列值并使用它们。

        方法不正确且已折旧,但有效:

        $type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
        $typeResult = mysql_query($type);
        // for each row
        while ($row = mysql_fetch_array($typeResult)) {
            // grab the columns
            $value = $row['column_name'];
        }
        

        我会推荐使用 MySQLi 或 PDO 之类的(MySQLi):

        $mysqli_connection = new mysqli("hostname", "username", "password", "database");
        $type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
        $res = $mysqli_connection->query($type);
        while($row = $res->fetch_array(MYSQLI_ASSOC)) {
            $value = $row['column_name'];
        }
        $res->free();
        $mysqli_connection->close();
        

        【讨论】:

          猜你喜欢
          • 2020-01-15
          • 1970-01-01
          • 2022-01-01
          • 2018-03-13
          • 2016-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-05
          相关资源
          最近更新 更多