简体   繁体   中英

simple SQL query returns nothing

I'm using sqlsrv driver, and I'm trying to make a query like this:

$query  = "select * from products";
$result = sqlsrv_query($conn,$query);
echo $result;

This returns me nothing. What is wrong with the query or PHP code?

This is how it would be done with a mysql connection. I haven't used sqlsrv driver, so it may not work as is but you get an idea.

Bruno posted a link with sqlsrv driver detailed code.

The real issue is that you can't just echo $result . It's an array and you have to do it row by row or write a function that echoes the complete $result. That way you can also filter rows or columns and format every field as you like.

$query  = "select id, title, price from products";
$result = mysql_query($conn,$query);

$num=mysql_numrows($result);

$i=0;
while ($i < $num)
{
    $id=mysql_result($result,$i,"id");
    $title=mysql_result($result,$i,"title");
    $price=mysql_result($result,$i,"price");

    echo "<b>id: $id</b> Product: $title , Price: $price<br>";

    $i++;
}

I agree with that the real problem is that you can't echo a result - you have to iterate through the results. Just so you have an example with the sqlsrv extension, here's how I'd do it:

$query = "select id, title, price from products";
$result = sqlsrv_query($conn, $query);

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
   echo "<b>id: $row['id']</b> Product: $row['product'], Price: $row['price'];
}

-Brian

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM