PHP aceder a MSSQL Server

eXcept

Power Member
Viva.

Andei à procura de vários códigos em PHP para aceder a um MSSQL Server remoto, mas não consigo por a funcionar.

Alguem tem alguma função a funcionar que o faça, e que me possa fornecer, sff?

Obrigado
 
Este é o meu código pra me ligar:
$_con;

function connect( $bd="nome_da_bd", $usr="root", $psw="", $srv="localhost", $prt="", $ext="") {
global $_con;

if( $_con !== NULL )
return FALSE;

if( is_int($prt) )
$s = "{$srv}:{$prt}";
else
$s = $srv;

if( $ext != "" )
$_con = @mysql_connect( $s, $usr, $psw, TRUE, $ext );
else
$_con = @mysql_connect( $s, $usr, $psw );

if( $_con !== FALSE ) {
if( !mysql_select_db( $bd, $_con ) ) {
return FALSE;
}
}
else {
$_con = NULL;
return FALSE;
}
}

Faz connect e selecciona a base de dados.
A ligação fica na variavel $_con.
Para usares é só chamares a função com os detalhes da ligação ao servidor (ip, user, pass, etc).

Se precisares de alguma explicação avisa :)
 
Obrigado de qualquer forma, mas a minha pergunta era para ligar a MSSQL ( Microsoft SQL Server ). Com MySQL eu sei perfeitamente trabalhar, mas obrigado na mesma.
 
Podes usar PEAR DB?
Se podes entao faz algo assim:
PHP:
 1.  <?
 2.  ini_set("include_path", "/path/to/php/pear");
 3.  require_once('DB.php');
 4.  $type = "mssql";
 5.  $user = "mssqluser";
 6.  $pass = "password";
 7.  $host = "192.168.0.1";
 8.  $database = "php";
 9.  $dsn = "$type://$user:$pass@$host/$database";
10.  $dbconn = DB::connect($dsn);
11.  if (DB::isError($dbconn)) { die ($dbconn->getMessage()); }
12.  /*
13.  create table bebop (
14.      id INT,
15.      name VARCHAR(8),
16.      origin CHAR(2));
17.  */
18.  $values = array (
19.      "insert into bebop values ('0','Spike','MA')",
20.      "insert into bebop values ('1','Jett','AZ')",
21.      "insert into bebop values ('2','Faye','FL')",
22.      "insert into bebop values ('3','Ed','NM')",
23.      "insert into bebop values ('4','Ein','CO')"
24.      );
25.
26.  $result = $dbconn->query("select * from bebop");
27.  if(DB::isError($result)) { die ($result->getMessage());}
28.  if($result->numRows() == 0) {
29.      echo "<P>Populating the DB!<p>";
30.      for($i = 0; $i < sizeof($values); $i++) {
31.        $result2 = $dbconn->query($values[$i]);
32.        if (DB::isError($result2)) { die ($result2->getMessage());}
33.      }
34.      echo "<P>Done the DB! Reload Page<p>";
35.  } else {
36.      $result = $dbconn->query("select name, origin from bebop");
37.      if (DB::isError($result)) { die ($result->getMessage());}
38.      echo "<P>Default Fetch Mode (DB_FETCHMODE_ORDERED):";
39.      while($result->fetchinto($row)){
40.        echo "<br>" . $row[0] . " " . $row[1];
41.      }
42.      $result = $dbconn->query("select name, origin from bebop");
43.      $dbconn->setFetchMode(DB_FETCHMODE_ASSOC);
44.      echo "<HR>DB_FETCHMODE_ASSOC Fetch Mode:";
45.      while($row = $result->fetchRow()){
46.        echo "<br>" . $row['name'] . " " . $row['origin'];
47.      }
48.      $result = $dbconn->query("select name, origin from bebop");
49.      $dbconn->setFetchMode(DB_FETCHMODE_OBJECT);
50.      echo "<HR>DB_FETCHMODE_OBJECT Fetch Mode:";
51.      while($result->fetchinto($row)){
52.      echo "<br>" . $row->name . " " . $row->origin;
53.      }
54.  }
55.  $result->free();
56.  $dbconn->disconnect();
57.  ?>

Se as operaçoes sobre a base de dados nao forem muito complexas, pode usar DBX.
Enabling DBX support for Windows is very easy, since the DLL file for DBX has been precompiled and included in the basic PHP windows installation. Open your php.ini file in a text editor and search for the line that says:

extension_dir = ./

This line should point to the place where your PHP extensions reside. If you copied the extensions to the same directory as the php.ini file, then you do not need to modify the line. If you did not move the PHP extensions to the same directory as the php.ini file, then you need to edit the line to point to the correct directory, for example:

extension_dir = C:\Apache\php\extensions

Next, find the section in the php.ini file that says:

;Windows Extensions

This line will be followed by many lines of windows .dll extensions for php. To enable DBX support, uncomment (delete the semicolon at the beginning of the line) the line that contains the DBX library DLL:

extension=php_dbx.dll

After you have uncommented the line, save the file and restart the Apache Web server.

PHP:
1.  <html>
 2.  <head>
 3.  <title>A PHP-DBX URL Organizer</title>
 4.  <style type=text/css>
 5.    p, ul, td, h1, h2, h3 {font-family: verdana, helvetica, sans-serif;}
 6.  </style>
 7.  </head>
 8.  <body>
 9.  <?
10.  /*****
11.  * TABLE DEFINITION FOR THIS EXAMPLE:
12.  * create table URLS (
13.  * url VARCHAR(128) not null,
14.  * description TEXT,
15.  * primary key (url));
16.  *****/
17.  //define $MODULE as DBX_MYSQL, DBX_MSSQL, DBX_PGSQL, or your supported database
18.  $MODULE = DBX_PGSQL;
19.  $server = "192.168.0.5";
20.  $user = "psqluser";
21.  $password = "password";
22.  $database = "php";
23.  /* FUNCTIONS */
24.  function get_urls($dbconn, $sql) {
25.    $result = @dbx_query($dbconn, $sql);
26.    if ( $result == 0 ) {
27.      echo dbx_error($dbconn);
28.    } else {
29.      return $result;
30.    }
31.  }
32.  function url($action, $dbconn, $url, $description) {
33.    if($action == "add") {
34.      $sql = "insert into URLS values('$url', '$description')";
35.    }elseif($action == "delete") {
36.      $url = urldecode($url);
37.      $sql = "delete from URLS where URL = '$url'";
38.    }
39.    $result = @dbx_query($dbconn, $sql);
40.    if ( $result == 0 ) {
41.      echo "<P>ERROR ADDING URL: " . dbx_error($dbconn);
42.    } else {
43.      print("<p>$action : $url succeeded!<p>");
44.    }
45.  }
46.  /*** MAIN ***/
47.  $dbconn = dbx_connect($MODULE, $server, $database, $user, $password) or die("CANNOT CON
NECT TO DATABASE");
48.  ?>
49.  <h1>PHP DBX URL Organizer</h1>
50.  <form action=dbx_urls.php method=post>
51.  <p><b>Add a URL:</b>
52.  <br>URL: <input type="text" name="url" maxlength="128" value="http://"> Description: 
<input type="text" name="description"> <input type="submit" name="addurl" value="Add 
URL!">
53.  </form>
54.  <?
55.  if(isset($addurl)) {
56.    url("add", $dbconn, $url, $description);
57.  }
58.  if(isset($delete)) {
59.    url("delete", $dbconn, $delete, "");
60.  }
61.  $sql = "select * from URLS";
62.  $result = get_urls($dbconn, $sql);
63.  if(sizeof($result->data) == 0) {
64.    ?>
65.    <h3>Sorry, there are no URLs in the database. You should add some.
66.    <?
67.  } else {
68.    ?>
69.    <p>
70.    <table border=1 cellpadding=5 cellspacing=0 width=600>
71.    <tr><td><b>URL</b></td><td><b>Description</b></td><td>&nbsp;</td></tr>
72.    <?
73.    for($i = 0; $i < sizeof($result->data); $i++) {
74.      ?>
75.      <tr><td><a href=<?=$result->data[$i]['url']?>><?=$result->data[$i]['url']?></a></td>
76.      <td><?=$result->data[$i]['description']?></td>
77.      <td width=1><a href=dbx_urls.php?delete=<?=urlencode(
$result->data[$i]['url'])?>>delete</a></tr>
78.      <?
79.    }
80.    ?></table><?
81.  }
82.  ?>
83.  </body>
84.  </html>
 
Tenta este codigo:

<?php

$myServer = "localhost";

$myUser = "sa";

$myPass = "";

$myDB = "Northwind";

$s = @mssql_connect($myServer, $myUser, $myPass)

or die("Couldn't connect to SQL Server on $myServer");

$d = @mssql_select_db($myDB, $s)

or die("Couldn't open database $myDB");

?>

Vai tb a http://pt.php.net/manual/en/ref.mssql.php para mais detalhes

Cumps
 
Última edição:
localhost .. wtf?! ele não disse remoto?! :P
eXcept, isso não será a mesma coisa que ligar a um servidor local mas definindo o servidor com o nome do servidor ou o ip? Vê isto: http://pt.php.net/function.mssql-connect
ps: Não te esqueças é que o MSSQL para poder ser acedido remotamente tem que ter o protocolo TCP/IP enabled nas suas configurações de rede.
Alem disso, verifica se te estás a tentar ligar a um MSSQL ou a um MSDE 2000( que é uma versão mais reduzia e restricta do MSSQL Server, que, da forma como é configurado e por licença tambem, apenas pode ser acedido localmente).
MSDE 2000
 
Última edição:
Estou a ligar-me mesmo a MSSQL remoto, não é o MSDE... Já vi o help do php.net montes de vezes, alguns links na net, e não consigo ligar-me.

E ele pode ser acedido via TCP/IP, porque tenho um IIS e páginas em ASP a aceder-lhe. Precisava era de usar uma tabela com logins e passwords que ele tem, em PHP.

Daí ter pedido um script que tivesse a certeza que funcionasse. :(
 
O código do Galbne_PT parece correcto, a unica diferença nas ligações é mesmo o nome das funções que são diferentes, de resto, liga-se da mesma maneira.

Tenta fazer o TRY CATCH para ver que erro te dá... Pode ser que o utilizador com o qual te estás a ligar não tem permissões para se ligar de onde se está a ligar, ou seja, pode não ser erro do lado do Php mas sim do lado do SQL2000...
De qualquer forma, quando dizes remotamente, dizes pela Net ou só na rede?!?!?!
 
Às voltas com o PEAR, o resultado que me aparece é
Código:
DB Error: extension not found

Ando às voltas com isto, e não consigo ver como resolver... :|

Alguma ideia?


Uma outra opção que tenho é fazer o export do conteudo daquela tabela que preciso da DB ( logins e passwords ), de x em x tempo, por exemplo de meia em meia hora, exportá-la para SQL e depois importá-la para o MySQL. Alguem sabe se é possível criar uma rotina destas no MSSQL?
 
eXcept disse:
Às voltas com o PEAR, o resultado que me aparece é
Código:
DB Error: extension not found

Ando às voltas com isto, e não consigo ver como resolver... :|

Alguma ideia?


Uma outra opção que tenho é fazer o export do conteudo daquela tabela que preciso da DB ( logins e passwords ), de x em x tempo, por exemplo de meia em meia hora, exportá-la para SQL e depois importá-la para o MySQL. Alguem sabe se é possível criar uma rotina destas no MSSQL?

tens a certeza que tens a extensao instalada?
com um erro desses...é provavél que nao ou entao nao esta activa ou enable
 
Back
Topo