So I am attempting to use MySQLi, however, I keep getting thrown the error
Fatal error: Call to a member function query() on null in
/home/u740966689/public_html/dashboard/API/infFunctions.php on line 78
I'm unsure why this is... I read up on some other questions and changed a few things such as how I connect to the database but I still get the error.
MY CODE:
File 1:
require 'infFunctions.php';
$DatabaseHost = '***';
$DatabaseUser = '***';
$DatabasePass = '***';
$DatabaseName = '***';
$mysqli = new mysqli("$DatabaseHost","$DatabaseUser","$DatabasePass","u740966689_site") or die ("infAPI | Could not connect to the database");
if (isset($_GET['Type'])){
$Type = $_GET['Type'];
if ($Type == 'Register') {
$Response = Signup($_GET['name'],$_GET['password'],$_GET['email']);
if ($Response == '1') {
$resp = 'success';
} else if ($Response == '2') {
$resp = 'error_one';
} else if ($Response == '3') {
$resp = 'error_two';
} else {
$resp = 'error_three';
}
echo $resp;
}
}
file 2:
function Signup($Username, $Password, $Email){
$UserArray = $mysqli->query("SELECT * FROM infWebAccounts WHERE Username='$Username'");
$UserArray2 = $mysqli->query("SELECT * FROM infPendingAccounts WHERE Username='$Username'");
if (mysqli_num_rows($UserArray) == 0 AND mysqli_num_rows($UserArray2) == 0){
$Password = hash("sha512",$Password);
$Query = $mysqli->query("INSERT INTO infPendingAccounts (Username,Password,Email,Verified) VALUES ('$Username','$Password','$Email',N')");
return '1';
}elseif (mysqli_num_rows($UserArray) > 0 ){
return '2';
}else{
return '3';
}
}
The $mysqli object is created in the global scope but you're trying to use it inside a function. This is in violation of PHP's scoping rules, where a child scope can't implicitly access state in a parent scope.
PHP Scoping Rules
You can work around it by either using global to explicitly indicate that you want to access a variable in the global scope (which is generally a bad idea and should be avoided as it can lead to spaghetti code), or add a parameter to your function that will allow you to pass the mysqli object in.
If you want to use a global variable you have to add this to the function.
Easily add global $mysqli; at the beginning of the Signup()-function
function Signup($Username, $Password, $Email)
{
global $mysqli;
$UserArray = $mysqli->query("SELECT * FROM infWebAccounts WHERE Username='$Username'");
$UserArray2 = $mysqli->query("SELECT * FROM infPendingAccounts WHERE Username='$Username'");
.
.
.
Check out PHP: Variable scope
In PHP global variables must be declared global inside a function if they are going to be used in that function.
The problem is with PHP variable scoping. Add global $mysqli inside Signup() function before you refer to the $mysqli variable:
function Signup($Username, $Password, $Email){
global $mysqli; // Add this line
$UserArray = $mysqli->query("SELECT * FROM infWebAccounts WHERE Username='$Username'");
$UserArray2 = $mysqli->query("SELECT * FROM infPendingAccounts WHERE Username='$Username'");
if (mysqli_num_rows($UserArray) == 0 AND mysqli_num_rows($UserArray2) == 0){
$Password = hash("sha512",$Password);
$Query = $mysqli->query("INSERT INTO infPendingAccounts (Username,Password,Email,Verified) VALUES ('$Username','$Password','$Email',N')");
// $rTech = new Roblox();
// $rTech -> DoLogin($rTech->password);
// $rTech -> SendPM($rTech->GetUserID($Username),"RDS Owner Analytics Site Verification","Please goto the site and verify with : \n" . hash("sha512",$Username.$Password));
return '1';
}elseif (mysqli_num_rows($UserArray) > 0 ){
return '2';
}else{
return '3';
}
}
or you can simply pass your connection variable as parameter in your SignUp function
function Signup($Username, $Password, $Email, $mysqli){
}
Learn more about variable scoping here: http://php.net/manual/en/language.variables.scope.php
Related
This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 6 years ago.
// db.php
$db = array();
$db['host'] = '127.0.0.1';
$db['login'] = 'root';
$db['pass'] = '';
$db['name'] = 'edziennik';
$db_conn = new PDO('mysql:host='.$db['host'].';dbname='.$db['name'].';charset=utf8mb4', $db['login'], $db['pass']);
login_system.php
<?php
require_once('cfg/db.php');
function validate_data($l, $p)
{
$query = "SELECT * FROM e_users WHERE login='"+$l+"' AND password='"+$p+"'";
$stmt = $db_conn->query($query);
$row_count = $stmt->rowCount();
if($row_count===1)
return true;
else
return false;
return false;
}
Error: Call to a member function query() on null
Adding global prefix don't helped.
I lost lot of time to fix it, so i ask you.
$db_conn doesn't exist in the validate_data scope. Pass it in as an argument.
<?php
require_once('cfg/db.php');
function validate_data($db_conn, $l, $p)
{
$query = "SELECT * FROM e_users WHERE login='".$l."' AND password='".$p."'";
$stmt = $db_conn->query($query);
$row_count = $stmt->rowCount();
if($row_count===1)
return true;
else
return false;
return false;
}
And when you call it, pass in the connection.
$check = validate_data($db_conn, $whateverLIs, $whateverPIs);
Edit: -Fixed concat operator as noted by #Bamar.
I have no records in a table called assessment
I have a function:
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
I call the function thus:
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
However my function is printing out nothing when I was expecting FALSE. It prints out true when there's a record.
When I get the result in $thereisdata I want to check for if its TRUE or FALSE but its not working.
I looked at the php manual boolean page but it didn't help
It seems that you are passing the database connection as an object using the variable $c in your function parameter. This tells me that you would greatly benefit by creating a class and using private properties/variables. Also, there are many errors in your code that shows me what you are trying to achieve, some errors are the way you are closing your db connection using the wrong variable, or how you place the close connection method after the return, that will never be reached.
Anyway, I would create a database class where you can then call on specific functions such as the check_assessment_record() as you wish.
Here's how I would redo your code:
<?php
class Database {
private $conn;
function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$this->conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
function check_assessment_record($p_id, $a_id) {
$sql = "SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
echo '<p>set $de = true</p>';
$de = TRUE;
} else {
echo '<p>set $de = false</p>';
$de = FALSE;
}
return $de;
}
function __destruct() {
$this->conn->close();
}
}
$p_id = 1;
$a_id = 2;
$db = new Database();
$record = $db->check_assessment_record($p_id, $a_id);
var_dump($record);
?>
are you using PDO's correctly?
A call for me would normally look like;
$aResults = array();
$st = $conn->prepare( $sql );
$st->execute();
while ( $row = $st->fetch() ) {
//do something, count, add to array etc.
$aResults[] = $row;
}
// return the results if there is, else returns null
if(!empty($aResults)){return $aResults;}
if you didnt want to put the results into an array you could just check if a column is returned;
$st = $conn->prepare( $sql );
$st->execute();
if(! $st->fetch() ){
echo 'there is no row';
}
Here is the code
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
You can check the return value using if else condition as
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
if($thereisdata){ print_f('%yes data is present%'); }
else{ print_f('% no data is not present %'); }
The reason is , sometime function returning Boolean values only contain the true value and consider false value as null , that's why you are not printing out any result when data is not found.
Hope this will help you. Don't forget to give your review and feedback.
This is my code in config.php file:
<?php
$db_username = 'name';
$db_password = 'my password';
$db_name = 'my db';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if ($mysqli->connect_error) {
throw new Exception("Error in Database Connection!");
}
?>
Now I have separate function.php with class commonFunctions
<?php
require_once '../config/config.php';
class commonFunctions {
function doLogin(){
global $mysqli;
$result = $mysqli->query("SELECT * FROM table WHERE itemcolor = 'red'") ;
$row_cnt = $result->num_rows;
return $row_cnt;
}
}
$common=new commonFunctions();
?>
Here I am using global $mysqli; to access $mysqli from config, which may not be a appropriate way to program and using global $mysqli; in every function to access $mysqli looks so bad.
Can you guys pls suggest better and clean way.
Thanks
It depends what programming paradigm you're comfortable with. Personally I like my PHP to be Object Orientated (OO), so i'd put the mysql in a new class called DB or something and then when I want to run the query i'd do $db->query('blabla').
class DB {
private $db;
function __construct() {
$dbConfig = Main::app()->config['db'];
$this->db = new \mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['pass'], $dbConfig['db']);
}
public function query($query, $where = false) {
if (!empty($where)) {
if (strpos(strtolower($where), 'where') > 0)
$query .= ' ' . $where;
else
$query .= ' WHERE ' . $where;
}
$result = $this->db->query($query);
if (!isset($result) || $result === false) {
dd([$query, $this->db->error, $where]);
}
/* will return true on INSERT / UPDATE queries */
if ($result !== true)
return $result->fetch_all(MYSQL_ASSOC);
}
}
Maybe you might just want to create a function in commonFunctions that handled all queries?
function query($query) {
global $mysqli;
return $mysqli->query($query);;
}
I'm trying to create a search feature on my website. It isn't showing any results and I keep getting Call to a member function prepare() on a non-object in line x...
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td>'.$eName.'</td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
I have my PDO connection included in my functions.php file.
prepare() is a method of a PDO connection object, and your $conn variable is not one. It needs to be instantiated as a connection object, like this:
$conn = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');
Or if that's already done somewhere in the "global" scope, you just need to declare in your function:
global $conn;
It's fine to do this. The declaration is misleading. It's only "global" in the scope of the executing script, and does not transcend the script execution. All such objects are destroyed at the end of script execution. It's nothing to do with the session.
should be like:
$sql = "SELECT * FROM entries
WHERE name LIKE :searchq or
description LIKE :searchq or
content LIKE :searchq";
global $conn;
$stmt = $conn->prepare($sql);
Make sure you have included the db configuration file.
I'm trying to check if there is an existing user in the database, and I keep getting this error when trying to check for the username in the database.
Call to a member function rowCount() on a non-object
^this is the error
Here is the top of register.php:
<?php
session_start();
require("database.class.php");
$dbn = new database(); // Define a new instance of the class "database".
$dbn->init("localhost", "root", "", "mrl-lr"); // Run the init function inside of "database" to set database connection parameters.
$db = $dbn->connect(); // Finally, run the connection and get a fully functional database connection!
?>
Here is the USERNAME code from the register.php:
// Step 5) Check if the username has not been entered.
if (!isset($_POST['username']) or empty($_POST['username'])) // ! = not; if not isset $_POST['username'] or empty $_POST['username'] then
{
// Step 5, 1) Log an error about the username not being entered.
$errors[] = "Username has not been entered!"; // [] is called "pushing" - pushing puts items into an array(in our case, errors).
} else {
// Step 5, 2) Check other validations.
// Step 5, 2, 1) RegEx Checking
if (!preg_match("/^[a-zA-Z0-9\s-\pL]+$/u", $_POST['username']))
{
$errors[] = "Username may only be numbers, letters and -'s!";
}
// Step 5, 2, 2) Check to see if the username is less than 4 chars or more than 46.
if (strlen($_POST['username']) <= 4 or strlen($_POST['username']) >= 46)
{
$errors[] = "Username must be 5-45 characters long.";
}
$count = $db->prepare("SELECT * FROM `users` WHERE `username`=?");
$user = strip_tags(addslashes($_POST['username']));
$count->bindParam(1, $user, PDO::PARAM_STR);
$count = $count->execute();
if ($count->rowCount() == 1)
{
$errors[] = "Time to be original! That user already exists!";
}
}
here is the code from database.class.php
<?php
class database
{
protected $host = "";
protected $user = "";
protected $pass = "";
protected $dbname = "";
public function init($host, $user, $pass, $dbname)
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->dbname = $dbname;
}
public function connect()
{
$connection = new PDO("mysql:host=".$this->host.";dbname=".$this->dbname, $this->user, $this->pass);
return ($connection ? $connection : false);
}
public function hashit($string, $salt)
{
return hash("whirlpool", $salt.$string.$salt);
}
}
?>
You should not re-assing the $count variable in this line:
$count = $count->execute();
Instead it should look like this:
$res = $count->execute();
Explenation: the execute() method returns a boolean indicating whether the execution succeded or not. In your code you are overwriting the $count statement with that boolean.
Your issue is that you are getting no result from the database, so you can't retrieve the row count. What you need to do is something more like this:
$stmt=$db->prepare("SELECT * FROM Document");
$stmt->execute();
if ($row = $page->fetch(PDO::FETCH_ASSOC)) {
// logic for true
}
You can read about PDO's fetch here
Edit: By the way, the prepared statement should be stripping the tags and adding slashes for you. That part is redundant.
Also, you have errors defined as an array, but you keep overwriting the whole array instead of adding to it. Try array_push