Função mssql_connect( )

Veja abaixo um exemplo de como se conectar a um banco de dados Microsoft SQL Server através da sua aplicação PHP, listando todos os dados da consulta e efetuando contagem dos registros, utilizando a funçãomssql_connect( ). A mesma está habilitada em servidores Windows 2003:

Arquivo: mssql.php

<? // Dados do banco $dbhost   = "hostbanco";   #Nome do host $db       = "nomebanco";   #Nome do banco de dados $user     = "nomeusuario"; #Nome do usuário $password = "senhabase";   #Senha do usuário  // Dados da tabela $tabela = "nometabela";    #Nome da tabela $campo1 = "campo1tabela";  #Nome do campo da tabela $campo2 = "campo2tabela";  #Nome de outro campo da tabela  @mssql_connect($dbhost,$user,$password) or die("Não foi possível a conexão com o servidor!"); @mssql_select_db("$db") or die("Não foi possível selecionar o banco de dados!");   $instrucaoSQL = "SELECT $campo1, $campo2 FROM $tabela ORDER BY $campo1"; $consulta = mssql_query($instrucaoSQL); $numRegistros = mssql_num_rows($consulta);   echo "Esta tabela contém $numRegistros registros!/n<hr>/n";   if ($numRegistros!=0) {  while ($cadaLinha = mssql_fetch_array($consulta)) {   echo "$cadaLinha[$campo1] - $cadaLinha[$campo2]/n<br>/n";  } } ?>

Função sqlsrv_connect( )

Neste outro exemplo é mostrado um script de conexão utilizando a função sqlsrv_connect( ). A mesma está habilitada em servidores Windows 2008:

Arquivo: sqlsrv.php

<? // Dados do banco $dbhost   = "hostbanco";   #Nome do host $db       = "nomebanco";   #Nome do banco de dados $user     = "nomeusuario"; #Nome do usuário $password = "senhabase";   #Senha do usuário   // Dados da tabela $tabela = "nometabela";    #Nome da tabela $campo1 = "campo1tabela";  #Nome do campo da tabela $campo2 = "campo2tabela";  #Nome de outro campo da tabela  $conninfo = array("Database" => $db, "UID" => $user, "PWD" => $password); $conn = sqlsrv_connect($dbhost, $conninfo);   $instrucaoSQL = "SELECT $campo1, $campo2 FROM $tabela ORDER BY $campo1";   $params = array(); $options =array("Scrollable" => SQLSRV_CURSOR_KEYSET); $consulta = sqlsrv_query($conn, $instrucaoSQL, $params, $options); $numRegistros = sqlsrv_num_rows($consulta);   echo "Esta tabela contém $numRegistros registros!/n<hr>/n";   if ($numRegistros!=0) {  while ($cadaLinha = sqlsrv_fetch_array($consulta, SQLSRV_FETCH_ASSOC)) {   echo "$cadaLinha[$campo1] - $cadaLinha[$campo2]/n<br>/n";  } } ?>

Provider SQLOLEDB

Neste outro exemplo é mostrado um script de conexão utilizando o Provider SQLOLEDB:

Arquivo: PDO_SQLOLEDB.php

<? // Dados do banco $dbhost   = "hostbanco";   #Nome do host $db       = "nomebanco";   #Nome do banco de dados $user     = "nomeusuario"; #Nome do usuário $password = "senhabase";   #Senha do usuário  // Dados da tabela $tabela = "nometabela";    #Nome da tabela $campo1 = "campo1tabela";  #Nome do campo da tabela  $conn = new COM ("ADODB.Connection") or die("Nâo foi possível carregar o ADO"); $connStr = "PROVIDER=SQLOLEDB;SERVER=".$dbhost.";UID=".$user.";PWD=".$password.";DATABASE=".$db; $conn->open($connStr);   $instrucaoSQL = "SELECT $campo1 FROM $tabela"; $rs = $conn->execute($instrucaoSQL);   $num_columns = $rs->Fields->Count(); echo "Foi mostrada $num_columns coluna da presente tabela.". "<br><br>";   for ($i=0; $i < $num_columns; $i++) {  $fld[$i] = $rs->Fields($i); }   echo "<table>";   while (!$rs->EOF) {  echo "<td>";  for ($i=0; $i < $num_columns; $i++)  {   echo "<td>" . $fld[$i]->value . "</td>";  }  echo "</td>";  $rs->MoveNext(); }   echo "</table>";   $rs->Close(); $conn->Close();   $rs = null; $conn = null; ?>

</source>

PDO(PHP Data Objects) com SQL Server

Neste exemplo é mostrado um script de conexão utilizando PDO(PHP Data Objects). Lembrando que este exemplo funciona na versão 5.2 do PHP. Para utilização em servidores Windows 2008, há de alterar a versão do php via web.config tendo em vista que a versão padrão em windows 2008 é a PHP 5.3:

Arquivo: PDO_SQLserver.php

<?php try {     $hostname = "sqlserver01.bancodedados.com";     $dbname = "nomebanco";     $username = "nomebanco";     $pw = "senha";     $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");   } catch (PDOException $e) {     echo "Erro de Conexão " . $e->getMessage() . "/n";     exit;   }       $query = $pdo->prepare("select Coluna FROM nome_tabela");       $query->execute();         for($i=0; $row = $query->fetch(); $i++){         echo $i." - ".$row['Coluna']."<br/>";       }         unset($pdo);        unset($query); ?>

Atenção: O código mencionado acima é somente um exemplo. Caso haja dúvidas quanto sua utilização, sugerimos que verifique juntamente a um desenvolvedor de sua confiança.

Veja também


Esse artigo ajudou você?

54 respostas para “Conectando-se ao MS SQL Server através do PHP”

  1. double strap on

    Thanks for the good writeup. It in fact used to be a enjoyment account it. Look complex to far introduced agreeable from you! By the way, how can we communicate?

    Responder
  2. beautiful lingerie

    Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Fantastic. I’m also an expert in this topic so I can understand your effort.

    Responder
  3. ליווי בישראל

    אסייתית קטנה ולוהטת מגיעה לביקור מיוחד אצל הרופא אשר בודק אותה לעומק…
    ליווי במרכז

    Responder
  4. digital signage

    The root of your writing while sounding reasonable initially, did not settle properly with me after some time. Somewhere within the sentences you managed to make me a believer but only for a very short while. I still have got a problem with your leaps in assumptions and one would do nicely to fill in all those gaps. In the event you actually can accomplish that, I will definitely end up being amazed.

    Responder
  5. How does Skincell Pro work?

    Your style is very unique in comparison to other folks I have read stuff from. I appreciate you for posting when you have the opportunity, Guess I’ll just bookmark this page.

    Responder
  6. hicbdbye cbd

    Whats up very nice blog!! Man .. Beautiful .. Amazing .. I’ll bookmark your blog and take the feeds additionally…I’m happy to search out so many useful information right here within the publish, we want work out extra strategies on this regard, thanks for sharing. buy cbd oil pure cbd

    Responder
  7. שירותי ליווי

    2 זוגות שהשתעממו מהרגיל החליטו לבצע חילופי זוגות וליהנות קצת יותר
    נערות ליווי בחיפה

    Responder
  8. Skywalker OG Feminized Cannabis Seeds

    Hi there, I do believe your web site could be having browser compatibility problems. When I take a look at your site in Safari, it looks fine but when opening in IE, it has some overlapping issues. I merely wanted to provide you with a quick heads up! Besides that, great website.

    Responder
  9. christmas gifts for girlfriend

    Wow! This could be one particular of the most beneficial blogs We’ve ever arrive across on this subject. Basically Magnificent. I’m also a specialist in this topic therefore I can understand your effort.

    Responder
  10. MOTORCYCLE

    Great tremendous issues here. I¡¦m very satisfied to see your article. Thank you a lot and i am looking ahead to contact you. Will you please drop me a mail?

    Responder
  11. Christi Pomerance

    Having read this I believed it was very informative. I appreciate you finding the time and effort to put cara bermain blackjack this content together. I once again find myself spending a significant amount of time both reading and leaving comments

    Responder
  12. דירות דיסקרטיות ברמתן גן

    https://israelnightclub.com/נערות-ליווי-בחיפה/ כנסו לאתר הזה עכשיו ותהנו ממגון רחב של בנות הכי יפות בארץ אז למה אתם מחכים כנסו עכשיו

    Responder
  13. free horror

    Hi, I do think this is a great site. I stumbledupon it 😉 I will revisit yet again since i have book marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

    Responder
  14. accessories

    There is definately a lot to know about this topic. I like all the points you have made.

    Responder
  15. Eva Bidez

    You have a very nice layout for your blog, i want it to use on my site too , 

    Responder
  16. Ida Fugua

    There is noticeably a bundle to understand about this. I suppose you made certain nice points in features also.

    Responder
  17. Sean Pest Control

    If you are trying to find for the best extreminator company, look no further. These guys dominate! The best there is.

    Responder
  18. redirected here

    I just want to tell you that I am just newbie to blogs and seriously savored you’re blog site. Probably I’m going to bookmark your blog post . You absolutely come with wonderful article content. Regards for sharing with us your webpage.

    Responder
  19. Pretty Gaming

    I used to be able to find good advice from your articles.

    Responder
  20. Savanna Hallam

    Rather good post. I simply found your site not to mention was going to believe which i experience unquestionably appreciated searching your blog items. In fact We are registering to an individuals feed and I we imagine you compose once soon enough!

    Responder
  21. Tim Dawson

    Hey! I loved your blog post. Keep making blog posts like this. I’ll be back to see more articles like this. It’s very creative. Thanks again!

    Responder
  22. Sharita Bedford

    Thank you for your hard work. I love sucking dick btw hmu

    Responder
  23. Junie Schraub

    Néanmois, merci quant à la pureté des sujet mentionnés maintenant : on sait aujourd’hui s”interviewer sur la véritable signification de certains des arguments que vous déférez ci…

    Responder
  24. Room of choice delivery

    Hello there, You have done an excellent job. I’ll certainly digg it and personally recommend to my friends. I am sure they will be benefited from this web site.

    Responder
  25. Cristine Kimpton

    Its like you learn my thoughts! You seem to understand so much approximately this, such as you wrote the e-book in it or something. I believe that you could do with some to power the message home a bit, but other than that, that is fantastic blog. A fantastic read. I’ll certainly be back.

    Responder
  26. Jason

    I think this is one of the most important information for me.
    And i am glad reading your article. But wanna remark on few general
    things, The web site style is perfect, the articles is really great!

    Responder
  27. 출장마사지

    This is the right site for everyone who hopes to understand this topic. You understand a whole lot its almost tough to argue with you (not that I actually will need toÖHaHa). You definitely put a fresh spin on a topic that’s been discussed for ages. Wonderful stuff, just great!

    Responder
  28. Rocker BMX BMX à vendre

    Thank you for another excellent post. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I’m on the look for such info.

    Responder
  29. pier and beam foundation repair methods

    My brother recommended I might like this website. He was entirely right. This post truly made my day. You cann’t imagine simply how much time I had spent for this info! Thanks!

    Responder
  30. plumbing repair a fantastic read

    As I site possessor I believe the content material here is rattling great , appreciate it for your hard work. You should keep it up forever! Best of luck.

    Responder
  31. charity auto donation

    Ohh, its fastidious discussion about this article here at this web site, I hsve
    reaqd all that, so now me also commenting at this place.

    Responder
  32. 마사지알바

    Amazing. Master. You’re some sort of wizard. Appreciate you.

    Responder
  33. best home warranty

    Nicee blog here! Also your web site a loot up very fast!
    I ddesire my site loaded up as quickly as yours…

    Responder
  34. local plumbers redirected here

    Hmm it appears like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any tips and hints for first-time blog writers? I’d really appreciate it.

    Responder
  35. 무료 슬롯

    Best view i have ever seen !

    Responder
  36. VitalFlow

    I love it when people come together and share thoughts. Great website, continue the good work.

    Responder
  37. Milagros

    Excellent post. I was checking continuously this blog and I am impressed!
    Extremely useful information. I casre for such information a lot.
    I was looking for this certain information for a very long time.Thank you and good luck.

    Responder
  38. Playset assembly service

    Hi, i think that i saw you visited my site thus i came to “return the favor”.I’m trying to find things to enhance my website!I suppose its ok to use some of your ideas!!

    Responder
  39. נערות ליווי

    תחת חלומי ובחורה לוהטת – המתכון המושלם לסקס סוער ולוהט
    נערות ליווי באילת

    Responder
  40. 4 room renovation

    A formidable share, I simply given this onto a colleague who was doing a bit of evaluation on this. And he in fact purchased me breakfast because I discovered it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love reading more on this topic. If attainable, as you change into experience, would you mind updating your blog with extra particulars? It’s highly useful for me. Massive thumb up for this weblog publish!

    Responder
  41. porno

    I have not checked in here for some time as I thought it was getting boring, but the last several posts are good quality so I guess I¡¦ll add you back to my everyday bloglist. You deserve it my friend 🙂

    Responder
  42. Get the facts

    I simply want to mention I am newbie to blogging and truly enjoyed you’re web-site. Probably I’m likely to bookmark your website . You actually have remarkable articles and reviews. Thanks a bunch for sharing with us your website.

    Responder
  43. digital marketing real estate

    This design is wicked! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job. I really loved what you had to say, and more than that, how you presented it. Too cool!

    Responder
  44. roadside assistance

    I have been absent for some time, but now I remember why I used to love this web site. Thanks , I¡¦ll try and check back more frequently. How frequently you update your site?

    Responder
  45. look at more info

    Very interesting info!Perfect just what I was searching for!

    Responder
  46. alberta car towing

    I was curious if you ever considered changing the structure of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?

    Responder
  47. movies 123

    Well I really liked reading it. This information offered by you is very effective for good planning.

    Responder
  48. Commercial cleaning company

    I am also commenting to let you understand what a awesome encounter my child experienced visiting your webblog. She even learned such a lot of details, most notably what it is like to possess an awesome coaching heart to let certain people without hassle grasp chosen hard to do things. You actually exceeded visitors’ expectations. Many thanks for distributing these powerful, dependable, explanatory and in addition easy thoughts on that topic to Ethel.

    Responder
  49. more tips here

    I also believe that mesothelioma is a exceptional form of cancer malignancy that is generally found in those people previously exposed to asbestos. Cancerous cellular material form in the mesothelium, which is a defensive lining that covers the vast majority of body’s areas. These cells ordinarily form in the lining of the lungs, mid-section, or the sac that really encircles the heart. Thanks for expressing your ideas.

    Responder
  50. Alta Abels

    I simply want to tell you that I am very new to blogging and site-building and truly enjoyed your web site. Probably I’m want to bookmark your blog post . You amazingly have tremendous stories. Appreciate it for sharing with us your web site.

    Responder

Comente sobre este conteúdo! Escreva o que pensa, complemente, vamos discutir. O conhecimento é livre!