Undefined variable that is defined in the constructor - php

Hi I seem to be getting an error on my code that seems to say that I have not initialez my variable but th veriabile is initialized in the constructor:
Notice: Undefined variable: conn in D:\Program Files\xampp\htdocs\Tutorials\Login\classes\mysql.php on line 18
Fatal error: Cannot access empty property in D:\Program Files\xampp\htdocs\Tutorials\Login\classes\mysql.php on line 18
And this is my code:
<?php
require_once('includes/constants.php');
class Mysql{
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER , DB_USER , DB_PASSWORD , DB_NAME) or
die('There was a problem connecting to the database');
}
function verify_Username_and_Pass($un , $pwd){
$query = "SELECT *
FROM users
WHERE username = ? AND password= ?
LIMIT 1";
if($stmt = $this->$conn->prepare($query)){ //this is where the error points
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if($stmt->fetch()){
$stmt->close;
return true;
}
}
}
}
?>
The error is thrown at the first if statement.How can I solve it?

Replace
$this->$conn
with
$this->conn
on the line when you have the error.

$this->$conn
This is wrong, it should be
$this->conn

Related

Fatal error: Uncaught Error: Call to a member function prepare() on null [C:\xampp\htdocs\twitter\core\classes\user.php on line 19] [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 27 days ago.
On logging in, This error pops up.
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\twitter\core\classes\user.php:19 Stack trace: #0 C:\xampp\htdocs\twitter\includes\login.php(17): User->login('user#email.com', 'passwordofuser') #1 C:\xampp\htdocs\twitter\index.php(59): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\twitter\core\classes\user.php on line 19
I'm a beginner in PHP and was trying to validate the "entered" email and password by connecting it to SQL DATABASE. I wanted to display an "error" message if the email or password is not available in database.
This is user.php.
The error is at line 19.
$stmt = $this->pdo->prepare("SELECT `user_id` FROM `users` WHERE `email` = :email AND `password` = :password");
user.php
<?php
class User
{
protected $pdo;
function _construct($pdo)
{
$this->pdo = $pdo;
}
public function checkInput($var)
{
$var = htmlspecialchars($var);
$var = trim($var);
$var = stripcslashes($var);
return $var;
}
public function login($email, $password)
{
$stmt = $this->pdo->prepare("SELECT `user_id` FROM `users` WHERE `email` = :email AND `password` = :password");
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->bindParam(":password",md5($password), PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0)
{
$_SESSION['user_id'] = $user->user_id;
header('Location: home.php');
}
else
{
return false;
}
}
}
?>
Now, here is my connection.php
<?php
$dsn = 'mysql:host=localhost; dbname=tweety';
$user = 'root';
$pass = '';
try
{
$pdo = new PDO($dsn, $user, $pass);
}
catch(PDOException $e)
{
echo 'Connnection error! ' . $e->getMessage();
}
?>
Here is login.php
I know that this question is asked previously but i can't help myself find a solution.Any help would be appreciated.
WHAT I TRIED:
Tried checking for typo error in connection.php
Tried restarting my SQL server from XAMPP.
Tried referring other "stackoverflow" questions.
In user.php
Rename _construct to __construct. Now the constructor isn't executed, so the pdo variable will remain empty.
add below lines to catch your exact error in your connection.php
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
this will show your details error exception if any available.
I guess that the variable $getFromU is an instance of the User class. But you have not yet instantiated it before using it.

Trying to connect from iOS to MySQL Database using php ( HTTP POST )

Below is my sample code for my PHP program, and my database has already been created.
createteam.php:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
config.php:
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
DbConnect.php:
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect()
{
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
DbOperation.php:
<?php
class DbOperation
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
However when I use HTTP POST method using Postman in Chrome, it states this
Notice: Undefined index: name in D:\xampp\htdocs\TestServ\api\createteam.php on line 9
Notice: Undefined index: member in D:\xampp\htdocs\TestServ\api\createteam.php on line 10
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'iphone' in D:\xampp\htdocs\TestServ\includes\DbConnect.php on line 20
Failed to connect to MySQL: Unknown database 'iphone'
Warning: mysqli::prepare(): Couldn't fetch mysqli in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 20
Fatal error: Uncaught Error: Call to a member function bind_param() on null in D:\xampp\htdocs\TestServ\includes\DbOperation.php:21 Stack trace: #0 D:\xampp\htdocs\TestServ\api\createteam.php(18): DbOperation->createTeam(NULL, NULL) #1 {main} thrown in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 21
What does this mean, and what should I change?
Your first two errors are caused because of these two lines:
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
The error (Undefined index) tells you that you have some non-existing variables, in this case name and member from your $_POST[] variable. Make sure your POST request is correctly made, see undefined variable for more information.
Your third error (Warning: mysqli::__construct(): (HY000/1049)) is caused because there isn't a database called iphone in your database system. Check if you have typed it correctly or if you haven't yet created an actual database with the name iphone.
The last error is caused because of the first two errors, since name and member aren't (correctly) defined in your POST request they have been set to NULL and the mysqli library doesn't like that.

Warning: mysqli_query(): Couldn't fetch mysqli in <file> on line <number>

The view file
<?php
require('OrderModel.php');
session_start();
if(!isset($_SESSION['orderModel'])){
$newModel = new OrderModel();
$_SESSION['orderModel'] = $newModel;
} else{
$newModel = $_SESSION['orderModel'];
}
$newModel->addToBasket(1, 30);
echo $newModel->getItemName($newModel->basket[0][0]);
?>
The OrderModel file (simplified)
class OrderModel{
public $basket;
public $orderDate;
public $orderTime;
public $sent;
public $dbc;
public $customerOrderID;
public function __construct()
{
$this->dbc = require_once('../../db/config.php');
$this->basket = [];
}
public function addToBasket($itemNumber, $itemQuantity){
array_push($this->basket, [$itemNumber, $itemQuantity]);
}
public function getItemName($itemNum){
$query = "SELECT ItemName FROM item WHERE ItemID = $itemNum;";
$r = mysqli_query($this->dbc, $query); //Line 31
if($r){
return mysqli_fetch_row($r)[0];
}else{
echo mysqli_error($this->dbc); //Line 35
}
}
I can confirm that the config.php file is definitely configured correctly and is talking to the DB. In any rate, the code is:
<?php
define ('username', 'root');
define ('password', 'root');
define ('server', '127.0.0.1');
define ('database', 'alberto');
$dbc = mysqli_connect(server, username, password, database) OR DIE ('Could not connect to MySQL: ' . mysqli_connect_error());
mysqli_set_charset($dbc, 'utf8');
return $dbc;
?>
I am getting the following error messages from the view file:
Warning: mysqli_query(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 31
Warning: mysqli_error(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 35
I suspect the error is to do with the session, but I can't seem to find any answers from the threads posted so far.
Please kindly advise. Thank you.
Barmar is correct that $this->dbc is not a valid mysqli object. You are using the require_once with the file like a function. Make the config.php a class, and make the db connection from there. See here for an example of what I'm referring to. https://gist.github.com/jonashansen229/4534794

php - Call to a member function prepare() on a non-object in

I get this error:
Fatal error: Call to a member function prepare() on a non-object in /home/folder/public_html/includes/name.php on line 1768
This is the function:
function _FC_GET($typ, $data, $username){
global $dbh;
$stmt = $dbh->prepare("SELECT * FROM stats_clicks WHERE typ=:typ AND user=:username AND data=:data LIMIT 1;");
$stmt->bindParam(':typ', $typ);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':data', $data);
try {
$stmt->execute();
}
catch(PDOException $e) {
die( _OP_ERROR($e->getMessage(), __FILE__ ,__LINE__) );
}
$QUERY_DAT = $stmt->fetchAll();
return empty($QUERY_DAT['value']) ? 0 : $QUERY_DAT['value'];
}
And this is line 1768:
$stmt = $dbh->prepare("SELECT * FROM stats_clicks WHERE typ=:typ AND user=:username AND data=:data LIMIT 1;");
I can't seem to find what is causing this. I use the $dbh-prepare(); statement in other functions in the same file.
$dbh is not defined at that line. Check where you create the object $dbh if it is before the line 1768 or it is not in any condition which is not fulfilled.
Try this :
Look at here
Probably the cause of your connection.

PHP DB connection and password verification

I have three errors
Warning: mysqli_stmt::fetch() expects exactly 0 parameters, 1 given in
/Volumes/shared/Digital/_Websites/_TEST/qpm/classes/mysql.php on line
20
Notice: Trying to get property of non-object in
/Volumes/shared/Digital/_Websites/_TEST/qpm/classes/mysql.php on line
23
Notice: Trying to get property of non-object in
/Volumes/shared/Digital/_Websites/_TEST/qpm/classes/mysql.php on line
23
Here is my code
<?php
require_once 'includes/constants.php';
class mysql{
private $conn;
function __construct(){
$this->conn = $conn = new MySQLi(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME)
or die ('There was an error in the connection');
}
function verify ($un, $pwd){
$username = $un;
$password = $pwd;
if ($sth = $this->conn->prepare("SELECT pass FROM User WHERE username = '".$un."' LIMIT 1")) {
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
// Hashing the password with its hash as the salt returns the same hash
if (crypt($password, $user->hash) == $user->hash) {
return true;
} else {
return false; }
}//end of if;
}//end of verify
}//enfd of class
Just trying to get pass and return true if its the same or false if not
Thanks
Like many, many, many other php users, you are confusing 2 totally different APIs - mysqli and PDO.
Please, choose one, namely PDO, and make your code consistent with it.
Here goes the code with all the useless stuff taken out,
yet with proper things, namely prepared statements, added:
function verify ($un, $pwd)
{
$sql = "SELECT pass FROM User WHERE username = ?"
$sth = $this->conn->prepare($sql);
$sth->execute(array($un));
$pass = $sth->fetchColumn();
return (crypt($pwd, $pass) == $pass);
}
but note that this function of verify should not be a method of mysql class

Categories