0

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?

7
  • Does products exist? Is the connection pointing to the right database? Commented Mar 22, 2011 at 16:38
  • Yes, products exist, and the conn is conected to the database with that table. Commented Mar 22, 2011 at 16:38
  • 4
    have you tried turning it off and on again? :) Commented Mar 22, 2011 at 16:39
  • 2
    I'm not sure, but I think you need to fetch the rows returned. Here is an example I found: msdn.microsoft.com/en-us/library/cc296196%28SQL.90%29.aspx Commented Mar 22, 2011 at 16:40
  • 1
    What does sqlsrv_errors() show? What happens if you try "select count(1) from products" ? Commented Mar 22, 2011 at 16:42

2 Answers 2

2

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.