从查询中获取结果

时间:2012-10-25 19:11:44

标签: php mysql

  

可能重复:
  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);

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

4 个答案:

答案 0 :(得分:2)

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

请注意,如果您要编写新代码,则应使用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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您实际上并未获取查询结果。下面是两个使用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();

答案 3 :(得分:0)

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

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

或者如果您更喜欢OOP方法

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

相关问题