开发者

simple SQL query returns nothing

开发者 https://www.devze.com 2023-02-18 20:19 出处:网络
I\'m using sqlsrv driver, and I\'m trying to make a query like this: $query= \"select * from products\";

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

0

精彩评论

暂无评论...
验证码 换一张
取 消