Connection to sql database on several php pages

0

I'm creating a site where several pages need to connect to the bank to perform their operations, for example, I made a login system, so the user clicks on 'login' opens a bootstrap modal to enter the data . I created the page "validaLogin.php" to do the checks of the users and put a require "validalogin.php"; in the navbar to call such page. What happens is this: inside this page I make the connection to the bank to perform the operations, but when I open a page that also needs to connect to the bank, the error "connectMySQL" has already been declared and can not be redeclared.

In short: Two pages are calling the same connection function twice and gives the error, is there any way to make a single site-wide connection?

function conectaAoMySQL(){

  $conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
  
  if ($conn->connect_error)
    throw new Exception('Falha na conexão com o MySQL: ' . $conn->connect_error);

  return $conn;   
}
    
asked by anonymous 10.11.2017 / 12:44

3 answers

0

Create a connection file instead of a function for this, I'll show a form using a working example

connection.php

<?php
    $servername = "localhost"; /* pode deixar localhost */
    $username = "root"; /* nome do usuario do banco de dados */ 
    $password = "1521128"; /* senha do banco de dados caso exista senao deixa $password = "" */
    $dbname = "meubancodedados"; /* nome do seu banco de dados*/

    // Criando a conexão com o banco de dados
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Checando a conexão com o banco de dados
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
?>

And in the other files that you need to connect to, just put this at the beginning of the file

<?php include("conexao.php"); ?>

In this way the whole file will have a connection to the database, being able to have 100 lines of 10,000 without having to call the function several times, and, you will get connection to all necessary files in a simple way

    
10.11.2017 / 12:51
0

Always when multiple pages will execute requests or inclusions choose "require_once" or "include_once" because they avoid duplicate inclusions in cases where a page accidentally tries to call a file 2 times.

    
10.11.2017 / 12:51
0

Follow the code of the page "validaLogin.php".

<?php
include("conexaoMysql.php");

session_start();

function filtraEntradaV($dado){
    $dado = trim($dado);
    $dado = stripslashes($dado);
    $dado = htmlspecialchars($dado);
    return $dado;
};  

if($_SERVER["REQUEST_METHOD"] == 'POST'){
    $login = filtraEntradaV($_POST["login"]);
    $senha = filtraEntradaV($_POST["senha"]);


    $sql = "SELECT Login FROM usuario where Login = '$login' and Senha = '$senha' ";
    $resultado = $conn->query($sql);

    if($resultado->num_rows <= 0){
        echo "<script>alert('Dados incorretos')</script>";}
    else
        $_SESSION["login"] = $login;

}


?>

Follow the code on the other page     

include("conexaoMysql.php");

function filtraEntradaC($dado){
    $dado = trim($dado);
    $dado = stripslashes($dado);
    $dado = htmlspecialchars($dado);
    return $dado;
}   

if($_SERVER["REQUEST_METHOD"] == 'POST'){
    $msgErro = '';
    $nome = $email = $motivo = $mensagem = "";


    $nome = filtraEntradaC($_POST["nome"]);
    $email = filtraEntradaC($_POST["email"]);
    $motivo = filtraEntradaC($_POST["motivo"]);
    $mensagem = filtraEntradaC($_POST["mensagem"]);

    try{


        $sql = "
            INSERT INTO clinicamedica.contato(Id, Nome, Email, Motivo, Mensagem)
            values (null, ? , ? , ? , ?);
        ";

        $stmt = $conn->prepare($sql);

        $stmt->bind_param("ssss", $nome , $email , $motivo , $mensagem);

        if (! $stmt->execute())
            throw new Exception("Erro ao realizar o contato: " . $conn->error);


        $formProcSucesso = true;
        } catch (Exception $e){
            $msgErro = $e->getMessage();
        }
}
?>

When I submit the form to this other page it accuses the login and password of the validaLogin page are not defined.

    
10.11.2017 / 13:13