-3

I am building a web application in core PHP

i am unable to execute any queries and getting warning and fatal error

Warning: Undefined variable $conn in D:\xampp\htdocs\colerp\app\model\common\loginModel.php on line 7

Fatal error: Uncaught Error: Call to a member function prepare() on null in D:\xampp\htdocs\colerp\app\model\common\loginModel.php:7 Stack trace: #0

my project folder is structured below

app
-- controller
-----common
-------- loginController.php
-- model
-----common
-------- loginModel.php
-- view
-------- login.php

config.php
db.php
index.php

I think there is problem with accessing config.php inside my loginModel.php

In my view file - login.php, i have included the loginController.php and the controller file - loginController.php has loginModel.php where i have written function getPassword()

sample View

<?php 
require DIR_CONTROLLER . 'common/loginController.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title> Login - ERP</title>
  <meta content="" name="description">
  <meta content="" name="keywords">
 </head>
  <body>
  <form class="row g-3 needs-validation" action="<?php echo WEB_CONTROLLER . 'common/loginController.php';?>" method="POST" novalidate>
    <?=$csrf->input('my-form');?>
    <div class="col-12">
      <label for="yourUsername" class="form-label">Username</label>
      <div class="input-group has-validation">
        <span class="input-group-text" id="inputGroupPrepend">@</span>
        <input type="text" name="username" class="form-control" id="yourUsername" required>
        <div class="invalid-feedback">Please enter your username.</div>
      </div>
    </div>
    <div class="col-12">
      <label for="yourPassword" class="form-label">Password</label>
      <input type="password" name="password" class="form-control" id="yourPassword" required>
      <div class="invalid-feedback">Please enter your password!</div>
    </div>
    <div class="col-12">
      <button name="lgnSubmit" class="btn btn-primary w-100" type="submit">Login</button>
    </div>
  </form>
  </body>
  </html>

Sample controller

  <?php

session_start();
if (file_exists("../../../config.php")) {
    include_once("../../../config.php"); 
} 

// Include require LIB and LANG Files
require DIR_LIB.'csrf/php-csrf.php';

$csrf = new CSRF();


if(isset($_POST['lgnSubmit']) && $_SERVER['REQUEST_METHOD'] === 'POST'){

    if ($csrf->validate('my-form')) {

        $data = array();
        $username = $_POST['username'];
        $password = $_POST['password'];

        require DIR_MODEL.'common/loginModel.php';
        $hashedPwd = getPassword($username);


    }else{
        session_destroy();
        die('Error!! You are not Authorized to access. Please contact Administraror.');
    }
}

sample model

<?php

function getPassword($username){

    $sql = "SELECT password FROM user_auth WHERE username=?"; // SQL with parameters
    
    $stmt = $conn->prepare($sql); 
    $stmt->bind_param("s", $username);
    $stmt->execute();


    $result = $stmt->get_result(); // get the mysqli result
    $user = $result->fetch_assoc(); // fetch data  
    echo "<pre>";
    print_r($result);
    echo "<br>-----------------<br>";
    print_r($user);

    die();
    
}

sample Config

<?php
/** Path **/

define( 'ABSPATH'           , __DIR__ . '/' );
define( 'DIR_STORAGE'       , ABSPATH.'uploads/');
define( 'DIR_LIB'           , ABSPATH.'library/');
define( 'DIR_APP'           , ABSPATH.'app/');
define( 'DIR_CONTROLLER'    , DIR_APP.'controller/');
define( 'DIR_MODEL'         , DIR_APP.'model/');
define( 'DIR_VIEW'          , DIR_APP.'view/');

define( 'WEB_HOME'          , 'http://localhost/colerp/');
define( 'WEB_STORAGE'       , WEB_HOME.'uploads/');
define( 'WEB_APP'           , WEB_HOME.'app/');
define( 'WEB_CONTROLLER'    , WEB_APP.'controller/');
define( 'WEB_MODEL'         , WEB_APP.'model/');
define( 'WEB_VIEW'          , WEB_APP.'view/');

// DB
define( 'DB_HOSTNAME'   , 'localhost');
define( 'DB_USERNAME'   , 'root');
define( 'DB_PASSWORD'   , '');
define( 'DB_DATABASE'   , 'colerp');

require 'db.php';

sample DB.php

<?php

// Create connection
$conn = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

// Check connection
if ($conn->connect_error) {
  die("Database Connection failed: " . $conn->connect_error);
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
dee flor
  • 69
  • 1
  • 9
  • 3
    Is this not just a simple scope issue? `$con` is not visible inside that function so you would have to pass it as a parameter – RiggsFolly Sep 01 '23 at 07:35
  • 2
    Back to basics...learn about the "scope" of variables: https://www.php.net/manual/en/language.variables.scope.php – ADyson Sep 01 '23 at 07:37
  • 1
    Either as a parameter as suggested, or you can tell the function to use the global variable using `global $conn;` at the beginning of your function – Kaddath Sep 01 '23 at 07:40
  • My Bad.. Sending $conn to the function solved the issue Thanks @RiggsFolly – dee flor Sep 01 '23 at 07:41

1 Answers1

0

The $conn variable is not visible inside the model file due to its scope.

Have a look at variable scopes in PHP.

One solution would be importing the $conn variable as global.

function getPassword($username){

        global $conn;
    
        $sql = "SELECT password FROM user_auth WHERE username=?"; // SQL with parameters
        
        $stmt = $conn->prepare($sql); 
        $stmt->bind_param("s", $username);
        $stmt->execute();
    
    
        $result = $stmt->get_result(); // get the mysqli result
        $user = $result->fetch_assoc(); // fetch data  
        echo "<pre>";
        print_r($result);
        echo "<br>-----------------<br>";
        print_r($user);
    
        die();
        
    }
Jarmo T
  • 164
  • 4
  • 1
    This is not how `global` works in PHP. the variable should be declared as usually, but `global $conn;` should be added inside the `getPassword` function, at the beginning usually as it is clearer – Kaddath Sep 01 '23 at 07:52
  • @Kaddath You're right, I edited my answer. – Jarmo T Sep 01 '23 at 07:55