Tenho um script php que cadastra informações no MYSQL.
Tem um erro que que não to conseguindo resolver com o a classe PDO.
É esse erro aqui:
- Código: Selecionar todos
Notice: Undefined variable: pdo in C:\wamp\www\gat\clientes\cad_clientes.php on line 40
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\gat\clientes\cad_clientes.php on line 40
Agora vou explicar a estrutura desse código.
1- To usando o Wampserver para simular o servidor web.
2 - Dentro do diretório www, tenho o diretório gat com alguns arquivos,
vou citar os mais importante para tentar resolver o problema.
funcoes.php
configuration.php
3 - Dentro do diretório www, tem o subdiretório clientes, que tem o arquivo cad_clientes.php.
Conteúdo dos arquivos.
configuration.php
- Código: Selecionar todos
<?php
// Faz a conexão com o banco de dados MYSQL
try {
$hostname = "servidor";
$datadase = "banco_de_dados";
$username = "root";
$password = "";
$pdo = new PDO ("mysql:host=$hostname;dbname=$datadase","$username","$password");
} catch (PDOException $e) {
echo "Erro de Conexão: <br />" . $e->getMessage() . "\n";
exit;
}
?>
funcoes.php
- Código: Selecionar todos
<?php
@session_start();
# Abriga as funções mais importante
# Inicia o sistema
function inicia(){
if (file_exists(dirname(__FILE__)."/installation/index.php") ):
print "<script language= 'JavaScript'>location.href = 'installation/index.php'</script>";
else:
if (file_exists(dirname(__FILE__)."/configuration.php") ):
require_once(dirname(__FILE__)."/configuration.php");
else:
die ('O arquivo de configuração não foi localizado, contate o técnico e/ou administrador do sistema!');
endif;
endif;
}
# Checa se o usuário logado é administrador
function isAdmin(){
$sql2 = mysql_query("SELECT * FROM usuarios WHERE id = '$_SESSION[id2]' AND usuario = '$_SESSION[user]' AND nivel = '1'") or die (mysql_error());
$row3 = mysql_num_rows($sql2);
if($row3 > 0):
$nivel = $linha['nivel'];
return true;
else:
return false;
endif;
}
# Controle de acesso por sessão
function ProtectSystem(){
if ( ($_SESSION['empresa2'] == "") or ($_SESSION['user'] == "") or ($_SESSION['pass'] == "") ):
header ("Location: index.php?error=3");
exit();
endif;
}
# Print msg
function printMSG($msg=NULL , $tipo=NULL){
if ($msg != NULL):
switch($tipo):
case 'erro';
echo '<div class="erro">'.$msg.'</div>';
break;
case 'alerta';
echo '<div class="alerta">'.$msg.'</div>';
break;
case 'pergunta';
echo '<div class="pergunta">'.$msg.'</div>';
break;
default;
echo '<div class="sucesso">'.$msg.'</div>';
break;
endswitch;
endif;
}
?>
O impasse tá nesses dois arquivos funçoes.php e configuration.php.
cad_clientes.php
- Código: Selecionar todos
<?php
require_once("funcoes.php");
//require_once("configuration.php");
?>
<script>
<!--Inserindo mascara cpf, data, cep etc.-->
function formatar(src, mask) {
var i = src.value.length;
var saida = mask.substring(0,1);
var texto = mask.substring(i)
if (texto.substring(0,1) != saida) {
src.value += texto.substring(0,1);
}
}
</script>
<div class="title"> <img class="incone-service" border="0" src="images/incones/add_client.png" width="25" height="25" /> <h3>Cadastrar Cliente</h3></div>
<?php
if (isset($_POST['save'])):
// Pegando os dados
$cliente = addslashes(trim($_POST['cliente']));
$rg = addslashes(trim($_POST['rg']));
$cpf = addslashes(trim($_POST['cpf']));
$oe = addslashes(trim($_POST['oe']));
$data_emissao = explode("/", $_POST['data_emissao']);
$data_nascimento = explode("/", $_POST['data_nascimento']);
$endereco = addslashes(trim($_POST['endereco']));
$referencia = addslashes(trim($_POST['referencia']));
$cidade = addslashes(trim($_POST['cidade']));
$uf = addslashes(trim($_POST['uf']));
$bairro = addslashes(trim($_POST['bairro']));
$cep = addslashes(trim($_POST['cep']));
$sexo = addslashes(trim($_POST['sexo']));
$telefone_01 = addslashes(trim($_POST['telefone_01']));
$telefone_02 = addslashes(trim($_POST['telefone_02']));
$e_mail = addslashes(trim($_POST['e_mail']));
$data_cadastro = date('Y-m-d');
$data_emissao2 = $data_emissao[2] . "-" . $data_emissao[1] . "-" . $data_emissao[0];
$data_nascimento2 = $data_nascimento[2] . "-" . $data_nascimento[1] . "-" . $data_nascimento[0];
// Preparando para gravar os dados
$gravar=$pdo->prepare("INSERT INTO clientes(cliente,rg,cpf,orgao_emissor,data_emissao,data_nascimento,endereco,referencia,cidade,uf,bairro,cep,sexo,telefone_01,telefone_20,e_mail,data_cadastro) VALUES (:cliente,:rg,:cpf,:orgao_emissor,:data_emissao,:data_nascimento,:endereco,:referencia,:cidade,:uf,:bairro,:cep,:sexo,:telefone_01,:telefone_20,:e_mail,:data_cadastro)");
$gravar->bindValue(":cliente",$cliente);
$gravar->bindValue(":rg",$rg);
$gravar->bindValue(":cpf",$cpf);
$gravar->bindValue(":orgao_emissor",$oe);
$gravar->bindValue(":data_emissao",$data_emissao2);
$gravar->bindValue(":data_nascimento",$data_nascimento2);
$gravar->bindValue(":endereco",$endereco);
$gravar->bindValue(":referencia",$referencia);
$gravar->bindValue(":cidade",$cidade);
$gravar->bindValue(":uf",$uf);
$gravar->bindValue(":bairro",$bairro);
$gravar->bindValue(":cep",$cep);
$gravar->bindValue(":sexo",$sexo);
$gravar->bindValue(":telefone_01",$telefone_01);
$gravar->bindValue(":telefone_20",$telefone_02);
$gravar->bindValue(":e_mail",$e_mail);
$gravar->bindValue(":data_cadastro",$data_cadastro);
// Validando Cadastro
$select=$pdo->prepare("SELECT * FROM clientes WHERE rg=? AND cpf=?");
$select->execute(array($rg,$cpf));
if ($rg != "" && $cpf != ""):
if ($select->rowCount() == 0):
// Executa o Cadastro
$gravar->execute();
printMSG("Dados inseridos com sucesso!");
else:
printMSG("Números de documentos já cadastrados!","erro");
endif;
endif;
endif;
?>
<div> </div>
<form enctype="multipart/form-data" method="POST" name="" action="">
<table align="center" width="80%" border="0">
<tr> <td> <label id="" class="text-right">Cliente:</label> </td> <td><input type="text" name="cliente" title="Nome completo do cliente" value="" size="50" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">RG:</label> <td><input type="text" name="rg" title="Número da carteira de identidade do cliente" value="" size="20" maxlength="20" id="" class="box-left" /> <label id="" class="text-left"> CPF:</label> <input type="text" name="cpf" title="Número do CPF do cliente" OnKeyPress="formatar(this, '###.###.###-##')" value="" size="18" maxlength="18" id="" class="box-left" /></td> </tr>
<tr> <td> <label id="" class="text-right">Orgão Emissor:</label> <td><input type="text" name="oe" title="Nome do orgão emissor do RG" value="" size="20" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Data Emissão:</label> <td><input type="text" name="data_emissao" title="Data de emissão do RG" OnKeyPress="formatar(this, '##/##/####')" value="" size="10" maxlength="20" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Data Nascimento:</label> <td><input type="text" name="data_nascimento" title="Data de nascimento do cliente" OnKeyPress="formatar(this, '##/##/####')" value="" size="10" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Endereço:</label> <td><input type="text" name="endereco" title="Endereço do cliente" value="" size="50" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Referência:</label> <td><input type="text" name="referencia" title="ponto de referência" value="" size="30" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Cidade:</label> <td><input type="text" name="cidade" title="Nome da cidade onde mora" value="" size="20" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">UF:</label> <td><input type="text" name="uf" title="Nome do estado onde mora" value="" size="20" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Bairro:</label> <td><input type="text" name="bairro" title="Nome do bairro onde mora" value="" size="20" maxlength="50" id="" class="box-left" /> <label id="" class="text-left"> CEP:</label> <input type="text" name="cep" title="CEP da cidade onde mora" OnKeyPress="formatar(this, '#####-###')" value="" size="16" maxlength="50" id="" class="box-left" /></td> </tr>
<tr>
<td> <label id="" class="text-right">Sexo:</label> </td>
<td>
<select name="sexo" title="Sexo do cliente" id="" class="">
<option value="">Selecione</option>
<option value="masculino">Masculino</option>
<option value="feminino">Feminino</option>
</select>
</td>
</tr>
<tr> <td> <label id="" class="text-right">Telefone 01:</label> <td><input type="text" name="telefone_01" title="Telefone para contato" OnKeyPress="formatar(this, '## #### ####')" value="" size="20" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">Telefone 02:</label> <td><input type="text" name="telefone_02" title="Telefone para contato" OnKeyPress="formatar(this, '## #### ####')" value="" size="20" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td> <label id="" class="text-right">E-mail:</label> <td><input type="text" name="e_mail" title="Endereço eletrônico para contato do cliente" value="" size="35" maxlength="50" id="" class="box-left" /> </td> </tr>
<tr> <td><label id="" class="text-right">Ação:</label></td> <td><input type="submit" name="save" value=" Salvar " size="" id="" class="submit" /> <input type="reset" name="clear" value=" Limpar Campos " size="" id="" class="submit" /> </td> </tr>
</table>
</form>
Se eu coloco o arquivo configuration.php direto
no arquivo cad_clientes.php assim
- Código: Selecionar todos
<?php
require_once("./configuration.php");
?>
tudo funciona certinho, mais se eu colocar no cad_clientes.php o funcões.php assim.
- Código: Selecionar todos
<?php
require_once("funcoes.php");
?>
Aí dá esse erro.
O erro diz que a função preparar foi chamada a um não objeto.
Já pesquisei mais não encontrei nada parecido com o meu problema.
Como resolver esse problema, alguém me dá uma ajuda?