Optando pela versatilidade, o exemplo explica a conexão de um banco de dados a partir do arquivo de inicialização application.ini da estrutura do zend framework, que define as configurações básicas do software/site. Através dessa lógica definimos um adaptador PDO específico de acordo com o banco de dados utilizado (Mysql, MS SQL Server ou PostgreSQL) que integra-se a um módulo padronizado de classes e métodos que faz a conexão ser realizada. Veja a seguir os passos utilizados para definir essa conexão: Entre no arquivo application.ini dentro da pasta application/config e defina as seguintes configurações abaixo da parâmetro [production]:

MySQL

resources.db.adapter = “PDO_MYSQL”
resources.db.params.host = “ENDEREÇO DO SERVIDOR”
resources.db.params.username = “LOGIN DO BANCO DE DADOS”
resources.db.params.dbname = “NOME DO BANCO DE DADOS”
resources.db.params.password = “SENHA DO BANCO DE DADOS”
resources.db.params.charset = “TIPO DE CODIFICAÇÃO DO BANCO (EX.: utf8)”
resources.db.params.isDefaultTableAdapter = true

MS SQL SERVER

resources.db.adapter = “PDO_MSSQL”
resources.db.params.pdoType = “dblib”
resources.db.params.host = “ENDEREÇO DO SERVIDOR”
resources.db.params.username = “LOGIN DO BANCO DE DADOS”
resources.db.params.dbname = “NOME DO BANCO DE DADOS”
resources.db.params.password = “SENHA DO BANCO DE DADOS”
resources.db.isDefaultTableAdapter = “true”

PostGreSQL

resources.db.adapter = “PDO_PGSQL”
resources.db.params.host = ” ENDEREÇO DO SERVIDOR”
resources.db.params.username = “LOGIN DO BANCO DE DADOS”
resources.db.params.dbname = “NOME DO BANCO DE DADOS”
resources.db.params.password = ” SENHA DO BANCO DE DADOS”
resources.db.isDefaultTableAdapter = true

Exemplo

Gostaria de ver um exemplo real? Veja abaixo como o código foi desenvolvido para se conectar ao banco de dados MySQL:

Zend framework - conectando-se com um banco de dados

Para capturar os dados dessa conexão criada, basta utilizar o comando abaixo que pode ser empregado em qualquer classe do controlador IndexController.php localizado no caminho application/controllers/ :

$db = Zend_Db_Table::getDefaultAdapter();

IMPORTANTE: O comando acima funcionará a partir da versão 1.8 do zend framework e é essencial o uso do parâmetro ”’resources.db.isDefaultTableAdapter = "true" no arquivo "application.ini"

Possíveis erros de conexão

Zend framework - conectando-se com um banco de dados

Esse tipo de erro é muito comum ocorrer para versões inferiores a 1.8 que utilizam o comando Zend_Db_Table::getDefaultAdapter(); para conectar-se ao banco de dados. Nesses casos a solução pode ser dada por meio de uma conexão através da Factory, aplicado em qualquer classe de seu controlador. Veja os exemplos a seguir:

Factory MySQL

Zend framework - conectando-se com um banco de dados

Factory MS SQL Server

Zend framework - conectando-se com um banco de dados

Factory PostGreSQL

Zend framework - conectando-se com um banco de dados

Para maiores informações, veja a documentação da classe Zend_Db_Adapter no site oficial do Zend Framework.

Veja também


PDO(PHP Data Objects) é um módulo de PHP montado sob o paradigma Orientado a Objetos e cujo objetivo é prover uma padronização da forma com que PHP se comunica com um banco de dados relacional. Este módulo surgiu a partir da versão 5 de PHP. PDO, portanto, é uma interface que define um conjunto de classes e a assinatura dos métodos de comunicação com uma base de dados.

Por que usar PDO?

Antes da chegada do PDO, a linguagem PHP oferecia suporte à comunicação com diferentes modelos de SGBD através de módulos específicos. A maioria deles provia uma biblioteca de funções e utilizava um resource para representar a conexão e outro para representar um resultset (o resultado de uma consulta). As operações eram feitas sobre as variáveis de resource.

Cada driver implementava suas operações conforme imaginavam ser mais adequados. Embora alguns deles tivessem um funcionamento semelhante, a ordem dos parâmetros nem sempre era a mesma e podia causar uma certa confusão entre programadores.

Como conectar a um banco MySQL usando PDO

Testando a conexão

  <?php   $banco = new PDO('mysql:host=localhost;dbname=nome_do_banco', 'username','password')or print (mysql_error());   print "Conexão Efetuada com sucesso!";   ?>

Incluir dados

  <?php   $banco = new PDO('mysql:host=localhost;dbname=nome_do_banco', 'username','password');   $novo_cliente = array('nome'=>'José','departamento'=>'TI','unidade'=>'Paulista');   $banco->prepare('INSERT INTO clientes (nome,departamento,unidade) VALUES (:nome,:departamento,:unidade)')->execute($novo_cliente);   ?>

Pesquisando dados em base MySQL utilizando querys simples e stored procedures

Neste exemplo, é possível efetuar pesquisas em bases MySQL utilizando querys e stored procedures. Lembrando que para evitar conflitos, teste sua procedure antes de implementá-la em sua aplicação.

Arquivo: ProcedurePDO.php

<?php   //Dados de acesso $host = "Nome_do_Host"; $dbn  = "Nome_da_Base"; $user = "Nome_do_Usuário"; $pass = "Senha_da_Base";   $tabela = "Nome_da_Tabela";   try {  //Conectar  $ligacao = new PDO("mysql:dbname=$dbn; host=$host", $user, $pass);  $ligacao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    //Em caso de pesquisas, via procedures  //$pesq = "";  //$sql = "CALL Nome_da_procedure()";    //Em caso de querys  $pesq = "Nome_do_Campo";  $sql = "SELECT * FROM $tabela WHERE nome= :nome_param";    $resultados = $ligacao->prepare($sql);    //Definição de parâmetros  $resultados->bindParam(":nome_param", $pesq, PDO::PARAM_STR);  $resultados->execute();    echo'<p>'.$sql.'</p><hr>';    foreach($resultados as $linha)  {   echo '<p>';   //Nome do campo na tabela pesquisada   echo $linha["Nome_da_Coluna"];   echo '</p>';  }    echo '<hr><p>Resultados: '.$resultados->rowCount().'</p>';    //Desconectar  $ligacao = null; } catch(PDOException $erro) {  echo $erro->getMessage(); }   ?>

Como conectar a um banco SQL Server usando PDO

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); ?>

Arquivo: PDO_SQLserver.php

<?php try {     $hostname = "sqlserver01.bancodedados.com";     $dbname = "nomebanco";     $username = "nomebanco";     $pw = "senha";     $pdo = new PDO ("dblib: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); ?>

Veja também


Obter 2ª via de Boleto.

Detalhamento de fatura.

Reative seus serviços.

Aplicativo Central do Cliente Zend framework - conectando-se com um banco de dados

Esse artigo ajudou você?

50 respostas para “Zend framework – conectando-se com um banco de dados”

  1. Wiley Weber

    Having read this I thought it was really informative. I appreciate you spending some time and energy to put Baccarat online this article together. I once again find myself spending a lot of time both reading and commenting

    Responder
  2. דירות דיסקרטיות במרכז

    נערות ליווי בתל אביב שלום לכולם יש פה מספר קישורים שאני מאוד רוצה להמליץ לכולם כי באמת יש פה מידע מצויין עבור שירותי עיסוי בישראל

    Responder
  3. Pain In Hips And Thighs

    Aw, this was a really nice post. In concept I want to put in writing like this additionally – taking time and precise effort to make a very good article… however what can I say… I procrastinate alot and under no circumstances appear to get one thing done.

    Responder
  4. Seth Affiliate

    Awesome blog post! I’ll be back to view your next piece! Thank you!

    Responder
  5. Kasi Arends

    abc news is of course one of the most reputable news sources these days`

    Responder
  6. hicbdbye cbd for pain

    I am continuously invstigating online for posts that can facilitate me. Thanks! pure cbd for sale cbd gummies

    Responder
  7. view it now

    I just want to tell you that I am beginner to weblog and honestly enjoyed this page. Most likely I’m want to bookmark your website . You actually have beneficial posts. Thanks a lot for revealing your web page.

    Responder
  8. Colton Eligio

    many thanks for telling!. “Truth is generally the best vindication against slander.” by Abraham Lincoln..

    Responder
  9. friction hinges manufacturers

    I would like to thank you for the efforts you’ve put in writing this site. I am hoping the same high-grade site post from you in the upcoming also. Actually your creative writing abilities has encouraged me to get my own blog now. Really the blogging is spreading its wings fast. Your write up is a great example of it.

    Responder
  10. Pest Control

    If you are searching for the greatest extreminator company, look no further. These guys rock!

    Responder
  11. Emory Maddern

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

    Responder
  12. Valeri Ledwell

    I was really delighted to find this website on bing, just what I was looking for : D besides saved to favorites .

    Responder
  13. Last mile delivery

    Hello. magnificent job. I did not imagine this. This is a remarkable story. Thanks!

    Responder
  14. Lanita Hevey

    Woah! I’m really loving the template/theme of this blog. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between user friendliness and visual appeal. I must say you have done a amazing job with this. Also, the blog loads super quick for me on Opera. Excellent Blog!

    Responder
  15. Hip Dysplasia Dogs

    I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get got an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield this increase.

    Responder
  16. Kaye Cuccaro

    I just added this webpage to my rss reader, great stuff. Can’t get enough!

    Responder
  17. Good Snapchat Girls

    I really admire your writing! I love sucking dick btw hmu

    Responder
  18. Home Remedies For Gout In Foot

    Thanks for another great post. Where else may just anybody get that type of info in such an ideal means of writing? I’ve a presentation subsequent week, and I’m on the look for such info.

    Responder
  19. best medicare plan

    I enjoy reading through your website. Thanks!

    Responder
  20. E-Scout Vélos électriques à vendre

    Someone essentially help to make significantly posts I would state. This is the very first time I frequented your web page and so far? I surprised with the research you made to create this actual post amazing. Excellent task!

    Responder
  21. Best Plumbers San Diego site

    Hello.This post was extremely fascinating, especially because I was searching for thoughts on this matter last week.

    Responder
  22. 출장마사지

    bookmarked!!, I love your website!

    Responder
  23. buy home warranty

    Very nice post. I just stumbled upon your blog annd
    wanted to say that I’ve truly enjoyed surfing around your
    blog posts. In any case I will bee subscribing to yyour feed and
    I hope you write again very soon!

    Responder
  24. pier and beam foundation repair methods

    Whats up are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding knowledge to make your own blog? Any help would be greatly appreciated!

    Responder
  25. Dominique

    Hello, after reading this amazing article i am as well happy to share my
    familiarity here with mates!

    Responder
  26. VitalFlow supplement

    I’m excited to discover this page. I wanted to thank you for ones time just for this wonderful read!! I definitely loved every bit of it and i also have you bookmarked to see new things in your web site.

    Responder
  27. 마사지구인구직

    It’s a jealous article. It’s very incredible and fresh. Who can be you to write this particular special article?

    Responder
  28. plumbers near me continue reading this

    Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us useful information to work on. You have done a outstanding job!

    Responder
  29. Playset assembly service

    Hi there, I found your site via Google while looking for a related topic, your site came up, it looks good. I have bookmarked it in my google bookmarks.

    Responder
  30. Student Health Insurance

    Witth thanks for sharing your superb website!

    Responder
  31. home warranty companies in florida

    It is not my first time to go to seee this website,
    i am visiting this weeb page dailly and tqke good information from here all the time.

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

    הוא הצעיר מהחדר ליד אבל בשבילה זה לא מפריע – מילף סקסית בטירוף מזיינת בחור צעיר בסקס אנלי מופרע
    נערות ליווי בצפון

    Responder
  33. our website

    I just want to say I am very new to blogs and truly savored your web-site. Probably I’m going to bookmark your website . You surely come with very good well written articles. Thanks for revealing your web-site.

    Responder
  34. remodel house contractor

    Thanks a bunch for sharing this with all of us you really know what you are talking about! Bookmarked. Please also visit my site =). We could have a link exchange arrangement between us!

    Responder
  35. Bariatric Vitamins Chewable With Iron

    I’m very happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this best doc.

    Responder
  36. porno

    One thing I would really like to comment on is that weightloss program fast is possible by the suitable diet and exercise. An individual’s size not merely affects appearance, but also the general quality of life. Self-esteem, depressive disorder, health risks, along with physical capabilities are afflicted in weight gain. It is possible to just make everything right and at the same time having a gain. If this happens, a medical problem may be the root cause. While an excessive amount of food and not enough workout are usually accountable, common medical conditions and widespread prescriptions could greatly amplify size. Thx for your post right here.

    Responder
  37. Pool table refelting

    I believe that avoiding refined foods may be the first step to lose weight. They could taste fine, but refined foods have very little nutritional value, making you take in more simply to have enough vigor to get over the day. In case you are constantly feeding on these foods, transferring to grain and other complex carbohydrates will aid you to have more strength while having less. Thanks alot : ) for your blog post.

    Responder
  38. White glove furniture delivery

    You can definitely see your enthusiasm in the work you write. The world hopes for more passionate writers such as you who are not afraid to mention how they believe. All the time go after your heart. “Faith in the ability of a leader is of slight service unless it be united with faith in his justice.” by George Goethals.

    Responder
  39. revamp

    obviously like your web-site but you need to check the spelling on quite a few of your posts. A number of them are rife with spelling problems and I find it very troublesome to tell the truth nevertheless I’ll certainly come back again.

    Responder
  40. is digital marketing hard

    Would you be interested in exchanging hyperlinks?

    Responder
  41. important source

    Thank you a bunch for sharing this with all folks you really understand what you are speaking approximately! Bookmarked. Kindly also talk over with my site =). We may have a hyperlink exchange agreement among us!

    Responder
  42. roadside assistance

    I conceive you have noted some very interesting points , thankyou for the post.

    Responder
  43. alberta car towing

    I should say also believe that mesothelioma cancer is a extraordinary form of cancers that is typically found in all those previously subjected to asbestos. Cancerous tissue form in the mesothelium, which is a protective lining which covers many of the body’s organs. These cells commonly form in the lining in the lungs, mid-section, or the sac that encircles the heart. Thanks for discussing your ideas.

    Responder
  44. Maryland pool table movers

    Good – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related information ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your client to communicate. Nice task..

    Responder
  45. Bennie Bashir

    I just want to say I am just very new to blogs and truly enjoyed your web-site. Almost certainly I’m planning to bookmark your site . You certainly come with superb well written articles. Thank you for revealing your blog.

    Responder

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