Link to home
Start Free TrialLog in
Avatar of caryma
caryma

asked on

Connecting to MSSQL and Returning Rows

I am trying to connect to a SQL Database and just return all rows.  My code is below:

<?php

$hostname = "server_Name";
$username = "user_name";
$password = "pass_word";
$dbName = "test";

MSSQL_CONNECT($hostname,$username,$password);
MSSQL_SELECT_DB($dbName);

$query = "select Name from alpha where Name = "Michael Cary"";
print $query;
$result = MSSQL_QUERY($query);
print $result;
//$number = MSSQL_NUM_ROWS($result);
//print $number;
//$i=0;

//if ($number == 0) : print "There is no data to display...";
//     elseif ($number > 0) : print "Data:";
     
//     while ($i < $number) : $name = mssql_result($result,$i,"Data");          
//     print $name; print "";
//     $i++;
//     endwhile;
//endif; ?>
ASKER CERTIFIED SOLUTION
Avatar of andriv
andriv

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dkjariwala
dkjariwala

Try following code,

<?php

$hostname = "server_Name";
$username = "user_name";
$password = "pass_word";
$dbName = "test";

MSSQL_CONNECT($hostname,$username,$password) or die('Can not connect to MS SQL');
MSSQL_SELECT_DB($dbName) or die("Can not select database $dbName");

$query = "select Name from alpha where Name = "Michael Cary"";
print $query;
$result = MSSQL_QUERY($query) or die("Can not execute query $query. ")  ;

/// print $result; //No need to print value of result.

while($row = mssql_fetch_array($result))
{
     //mssql fetch array fetches one record in an array whose indices are name of the fields.

     $name = $row['Name'] ; //so you here user name of your field as index, i.e. 'Name
     print "Name is $name";
     //also mssql_fetch_array advances pointer to next record , so this while loop would go through all the results !!
}

?>

Check out my comments.
Also see how I have used the die function.

Hope that solves your problem,
JD

P.S. : Andriv, when dealing with mssql, you use mssql_fetch_array rather than mysql_fetch_array.

Just a simple mistype. Good answer I seen it somewhere before.
Force Accepted

SpideyMod
Community Support Moderator @Experts Exchange