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:
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
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
Factory MS SQL Server
Factory PostGreSQL
Para maiores informações, veja a documentação da classe Zend_Db_Adapter no site oficial do Zend Framework.
Veja também
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
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
- Conectando-se ao Postgre usando PDO
- Como alterar as diretivas do PHP
- Módulos PHP
- PHP em Plataforma Windows
- Criar Stored Procedures no PhpMyAdmin
Jestem pod wrażeniem Twojej głębokości uznania i ekspozycja umiejętność złożoną pytanie dostępną Pojemną pracę|To zarejestruj się to klejnot Więc uszczęśliwiony zacząłem to|Ty był uderzony zadziwiające pojemność do pisania atrakcyjna treść|To pismo na najwyższym poziomie zdobyłeś unfamiliar obserwującego|Twój enter był zarówno wnikliwy, jak i cudownie napisany|Jestem zdumiony przeszłość jak wiele au fait z tego posta|wykonujesz znaczną pracę To rekord jest ratyfikacją o tym} {https://kredytero.pl|kredytero.pl|kredyt|kredyty|kredyt online|kredyty online|kredyt przez internet|kredyty przez internet}!
ìåéä złożoną problem dostępną Świetną pracę|To post to klejnot Więc uszczęśliwiony konfigurowałem to|Ty był uderzony olśniewające zdolność do kasowania atrakcyjna treść|To pismo na najwyższym poziomie zdobyłeś modern obserwującego|Twój post był zarówno wnikliwy, jak i uroczo napisany|Jestem zdumiony przeszłość jak wiele dobrze wykształcony z tego posta|wykonujesz adept pracę To wysłanie jest dowodem o tym} {pożyczki online|pożyczki|pożyczki pozabankowe|http://pozyczkaland.pl/|pozyczkaland.pl/|pożyczka online|pożyczka|pożyczka pozabankowa}!
Every paragraph was a gratify to read Thank you.
This is top-notch writing You’ve earned a new follower https://bekaCryptogambling.com/.
I’m so glad I comprehend this You’ve in effect made me think.
You be struck by an astonishing adeptness to write appealing content.
You have an dazzling ability to write appealing content cynRealMoneyRoulette.com/.
You’re doing immense work This dispatch is stay of that where to play poker.
You’re a odd writer This post proves it yet again cyktexasholdem.com/.
Your postal service was both insightful and delightfully written.
You nailed it with this post Uncommonly helpful Texas Holdem online.
You’ve made a complex thesis accessible Large job https://onlinegamblingtit.com/.
Your register is both enlightening and entertaining A rare find sites for sports betting.
I’m in awe of your predisposition for writing This was brilliant https://onlinesportsbookpyk.com/.
I’m impressed with your perspicaciousness of knowledge and expos‚ skill betting sites.
Every paragraph was a gratify to read Thanks you.
Solely brilliant You father a acquiesce with words Sports Betting Bonuses.
This is top-notch writing You’ve earned a modern follower.
You’re doing adept work This dispatch is stay of that realmoneycasinobug.com/.
I’m impressed with your depth of facts and column skill
This article is a masterclass in [topic] Kudos to you casino game for real money.
I always look leading to your posts This was another treasure online casinos real money.
Your post was not lone instructive but also genuinely inspiring https://tuvcannabisoil.com/.
You compel ought to an dazzling capability faculty to set engaging content https://cbdoilsiv.com/.
You have a offering conducive to explaining complex topics easily.
Your collection was both insightful and delightfully written
Your insights are invaluable Really cognizant your work
This record is a gem So pleased as punch I start it installment loans us enjoyers.
This is some of the most appropriate script I’ve seen on this subject
Of course loved this notify – so insightful and well-written cost cheap sildenafil online.
I really got here cranny of your mail and turned into forthwith captivated in all respects your insights. Your slant is both clean and concept-provoking. it is evident that you’ve achieved big delve into, and your capacity to introduce the facts in an attractive attitude is wonderful. this is a rationale i’ve been interested in for the treatment of a while, and your post has provided me with a mark renewed outlook. thanks exchange for sharing your cialis for sale.
I’m thoroughly impressed by your latest blog post. The way you’ve articulated your points is nothing short of brilliant. Your balanced approach, blending in-depth research with personal anecdotes, makes your writing not only informative but also highly relatable bshnwmrih.wordpress.com/.
I’ve just finished reading your latest blog post, and I must say, it’s outstanding! The depth of your analysis coupled with your engaging writing style made for an exceptional read. What struck me most was your ability to break down complex ideas into digestible, relatable content. Your examples and real-life applications brought the topic to life. I’ve gained a lot from your insights and am grateful for the learning. Keep up the fantastic work – your blog is a treasure trove of knowledge!
Your latest blog post truly resonated with me! The depth of insight and the clarity of your thoughts are commendable. It’s evident that you’ve put a lot of thought and research into this topic, and it shows. Your ability to present complex ideas in such an accessible and engaging manner is a rare skill. Thank you for sharing your knowledge and perspective – it’s been a thought-provoking read and I’m already looking forward to your next piece!
I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to construct my own blog and would like to find out where u got this from. thanks a lot
Hello there, just became alert to your blog through Google, and found that it’s really informative. I’m going to watch out for brussels. I’ll appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!
A person essentially help to make seriously posts I would state. This is the first time I frequented your website page and thus far? I amazed with the research you made to create this particular publish amazing. Fantastic job!
Hi, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam feedback? If so how do you protect against it, any plugin or anything you can recommend? I get so much lately it’s driving me mad so any assistance is very much appreciated.
I’m still learning from you, while I’m improving myself. I definitely love reading everything that is posted on your blog.Keep the tips coming. I enjoyed it!
You completed a number of nice points there. I did a search on the issue and found nearly all people will have the same opinion with your blog.betflik
Great – I should definitely pronounce, impressed with your website. I had no trouble navigating through all the tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your customer to communicate. Excellent task..
Hello! I could have sworn I’ve been to this website before but after reading through some of the post I realized it’s new to me. Anyways, I’m definitely delighted I found it and I’ll be book-marking and checking back often!
A lot of of whatever you assert happens to be supprisingly appropriate and that makes me ponder the reason why I hadn’t looked at this with this light previously. This particular article truly did turn the light on for me personally as far as this particular subject goes. Nonetheless there is one issue I am not too cozy with and while I try to reconcile that with the core theme of your point, allow me observe exactly what all the rest of the visitors have to say.Very well done.
Hello my friend! I want to say that this post is amazing, nice written and include almost all important infos. I’d like to see more posts like this.
You completed a number of nice points there. I did a search on the issue and found nearly all people will have the same opinion with your blog.betflik