Connection to sql database on multiple php pages

Asked

Viewed 2,563 times

0

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

In short: Two pages are calling the same connection function with the bank twice and gives the error, there is some way to make a connection only for the whole site?

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;   
}

  • 1

    use require_once or include_once depending on your need rather than require alone or include alone

  • Search the design Pattern Lazy loading

3 answers

0

Whenever multiple pages will perform requests or inclusions choose "require_once" or "include_once" as they avoid duplicate inclusions in cases where a page accidentally tries to call a file 2 times.

  • I put include_once on both pages, in only on the validation pageLogin.php but did not resolve.

0


Create a connection file instead of a function for this, I will show a way using a functional example

php connection.

<?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 you need connection just put this at the beginning of the file

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

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

  • The connection error came out after I took the function, but now the problem is this, the login part is working normally, but when I submit another form on another page, it accuses two "Notices" warning that "login" and "password" the login form are not defined, the data is stored normally in the database but from these notices, know how to remove them?

  • Try to put an if(isset($_POST["login"]) && isset($_POST["password"])){calleFuncao} in the place that checks the login, so if these variables exist it logs in, otherwise it doesn’t even try.

  • open a new question and put her link below my comment, in a comment from you. Then we will help you, not to mess up this topic that can be of help to other users too

0

It follows code from 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 code from 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 of this other page it accuses that login and password of the validaLogin page are not defined.

  • the name of the connection file you created was this same ? connectionMysql ?

  • Yes, it was already created, I just removed the function of it and solved, but is with the error reported above.

  • put the session before login, and put the session in the second file will also be => session_start(); include("connectionMysql.php");

  • He submits both forms: Notice: A Session had already been Started - ignoring session_start() in C: xampp htdocs Clinicamedica php validalogin.php on line 2 Notice: Undefined index: login in C: xampp htdocs Clinicamedica php validalogin.php on line 13 Notice: Undefined index: password in C: xampp htdocs Clinicamedica php validalogin.php on line 14

  • is indicating that a session has already been started, try to verify otherwise it has two session_start flames()

  • Yes, the problem is in these variables, is there any way I can do this login check without calling the function in the navbar? Because the form needs to be in the modal

  • look do the following, open another question because otherwise will be 5 questions and answers in a single topic, and cite your new problems, delete this your answer, because it is also a question, and mark the answer that best met you, there as the best for other users to see that they already have a solution and no one half waste time trying to solve this problem that is already solved. Then you put the link of the new question here and I help you again ok ?

  • https://answall.com/questions/254256/login-no-modal-do-bootstrap

  • do not forget to remove this "answer now, so do not mess this topic, please

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.