Undefined variable/empty property error after access - php

This is driving me crazy and I hope someone can help.
I am learning PHP and as part of a larger project to help me debug/log issues as they happen I have created a PHP error logging class.
This is my error:
This is a test
I hope it worked!
Success!
Notice: Undefined variable: errorLog in /Applications/MAMP/htdocs/errorlog.php on line 27
Fatal error: Cannot access empty property in /Applications/MAMP/htdocs/errorlog.php on line 27
So I can see
The error on line 27 consists of:
$outputStringForSQL = $conn->escape_string($this->$errorLog);
I am stumped. I don't understand how $errorLog is undefined as it has clearly been added to twice with the append() method, and read from using the returnLog() method. The property $errorLog is clearly not empty as returnLog() reads from it fine. I have checked that $this->errorLog is not empty by echoing it out.
I thought maybe I misunderstood scope so set $erroLog to public, still nothing.
Here is errorlog.php the class 'errorlog':
<?php
class errorlog{
protected $errorLog;
public function append($string){
$this->errorLog = $this->errorLog . $string . "<br />";
}
public function returnLog() {
echo $this->errorLog;
return "Success!";
}
public function commit(){
global $_mysqlUsername;
global $_mysqlPassword;
$servername = "localhost";
$dbname = "my_DB"; //production
// Create connection
$conn = new mysqli($servername, 'root', 'root', $dbname);
// Check connection
if ($conn->connect_error) {
die(error_log($conn->connect_error));
}
$outputStringForSQL = $conn->escape_string($this->$errorLog);
$sql = "INSERT INTO `tblDebugLog` (`ID`, `dateTime`, `debugData`) VALUES (NULL, CURRENT_TIMESTAMP, '$outputStringForSQL');";
if ($conn->query($sql) !== TRUE) {
echo("Error: " . $sql . "<br>" . $conn->error);
}
$conn->close();
return 'Success';
}
}
?>
This is the script making use of the 'errorlog' class:
<?php
function __autoload($class){
require "$class.php";
}
$myError = new errorlog;
$myError->append('This is a test');
$myError->append('I hope it worked!');
echo $myError->returnLog();
echo $myError->commit();
?>
Can anyone shed some light on this bug?
Many thanks.

Replace $this->$errorLog to $this->errorLog

Related

Global Scope fails for included file

Can someone please help me with a scoping issue. I've been looking at this for so long and I just don't see why this isn't working:
connection.php
<?php
$hostname = "xxx.xxx.xxx.xxx";
$username = "xxxxxxxx";
$password = "xxxxxxxx";
$db_name = "xxxxxxxx";
function isSecure() {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
global $link;
$link = mysqli_connect($hostname, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
?>
builder.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$connection = $path . '/scripts/connection.php';
include_once ($connection);
session_start();
$club_id = $_SESSION['club_id'];
if (mysqli_connect_errno()) {
trigger_error("Failed to connect to MySQL: " . mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM Workout_types
WHERE club_id=$club_id
ORDER BY type";
$result = mysqli_query($link, $sql) or trigger_error("Error description:" . mysqli_error($link) . "done");
?>
and I get the dreaded
mysqli_query() expects parameter 1 to be mysqli, null given in...
error.
Implementing the troubleshooting tips below, I changed a couple of lines.
builder.php:
require_once ("../scripts/connection.php");
connection.php:
if (!$link) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
It still doesn't work, but the errors are a bit different:
PHP Warning: mysqli_query(): Couldn't fetch mysqli in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
PHP Warning: mysqli_error(): Couldn't fetch mysqli in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
PHP Notice: Error description:done in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
where line 114 is the mysqli_query line.
I checked the GoDaddy docs, and that path is correct.
Just to prove that my include path was correct, I added this to connection.php:
global $test;
$test = "hello world";
Then in builder.php, I added a line echo $test;, and it printed hello world with no trouble whatsoever.
I should mention two other things could be helpful:
The code that I posted for builder.php is embedded in html code for a web page. It's the only php code in that file.
I originally wrote this code about 5 years ago, and it's been functioning flawlessly until I upgraded the php version on my server from 5.6.40 to 7.3.27. That's when it began to fail.

Connection established to MariaDB server, but couldn't get data into database?

This is the whole php code:
<html>
<head>
<title>Connect to MariaDB Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'test';
$dbpass = 'pass';
$dbname = 'databseName';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br><br>";
function add($url, $category){
$sql = "INSERT INTO tt (url, category) VALUES ('$url', '$category');";
if(mysqli_query($conn, $sql)){
echo "Recorded.";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
if(function_exists($_GET['f'])){
$_GET['f']($_GET['url'], $_GET['cat']);
}
mysqli_close($conn);
?>
</body>
</html>
When I typed in "http://localhost/connect.php?f=add&url=www.google.com&cat=google" in my browser, this is the result:
Connected successfully
Error: INSERT INTO tt (url, category) VALUES ('www.google.com', 'google');
Notice: Undefined variable: conn in /var/www/html/connect.php on line 24
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/html/connect.php on line 24
Fatal error: Uncaught Error: Call to undefined function mysqli_errot() in /var/www/html/connect.php:27 Stack trace: #0 /var/www/html/connect.php(32): add('www.google.com', 'google') #1 {main} thrown in /var/www/html/connect.php on line 27
I tried a lot of other possible solutions I found online but none of them work. Please help, many thanks in advance!
In your function of:
function add($url, $category) {
// code
}
You are trying to use the variable $conn. Which is defined outside of the function.
You should pass that variable into the function:
function add($url, $category, &$conn) {
// code
}
if(function_exists($_GET['f'])){
$_GET['f']($_GET['url'], $_GET['cat'], $conn);
}
You could just use global $conn; inside the function, but it is suggested to avoid using global entirely. It makes for messy and dangerous code conditions in larger projects. Less control. By passing the $conn by reference, you are specifically ensuring the right value is going to be used.
As a side note: prepared statements would be good to use for your SQL since you are putting passed in values which can have malicious SQL inside them.
As a side side note: thiswhole process you are making looks a bit precarious and lots of care should be taken to whitelist function names and set up. You may wish to move it all to a class too.

Showing Error in a php function

I have declared a function called test_input in my php script,which working absolutely fine in another scripts.
It shows error
Fatal error: Uncaught Error: Call to undefined function test_input() in C:\xampp\htdocs\submitdata\cwisubmit.php:25 Stack trace: #0 {main} thrown in C:\xampp\htdocs\submitdata\cwisubmit.php on line 25
My php script is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Database Connected SUCCESSFULLY";
if($_SERVER["REQUEST_METHOD"]=="POST") {
// Variables initialization
$fname=$lname=$dob=$phone=$email=$postcode=$staddress=$city=$lan=$lcwi=$ptype=$mhtype="";
// Retrieving the data from the form
$fname=test_input(mysqli_real_escape_string($conn,$_POST['fname']));
$lname=test_input(mysqli_real_escape_string($conn,$_POST['lname']));
$dob=test_input(mysqli_real_escape_string($conn,$_POST['dob']));
$phone=test_input(mysqli_real_escape_string($conn,$_POST['phone']));
$email=test_input(mysqli_real_escape_string($conn,$_POST['email']));
$postcode=test_input(mysqli_real_escape_string($conn,$_POST['postcode']));
$staddress=test_input(mysqli_real_escape_string($conn,$_POST['staddress']));
$city=test_input(mysqli_real_escape_string($conn,$_POST['city']));
$lan=test_input(mysqli_real_escape_string($conn,$_POST['lan']));
$lcwi=test_input(mysqli_real_escape_string($conn,$_POST['lcwi']));
$ptype=test_input(mysqli_real_escape_string($conn,$_POST['ptype']));
$mhtype=test_input(mysqli_real_escape_string($conn,$_POST['mhtype']));
function test_input($data) {
$data=trim($data);
$data=stripslashes($data);
return $data;
}
//sql insert
$sql="INSERT INTO cwi(fname, lname, dob, phone, email, postcode, staddress, city, lan, lcwi, ptype, mhtype) VALUES('$fname','$lname','$dob','$phone','$email','$postcode','$staddress','$city','$lan','$lcwi','$ptype','$mhtype')";
if($conn->query($sql)===TRUE){
echo "<center>RECORDS UPDATED SUCCESSFULLY</center>";
}else{
echo "Error: ".$sql."<br>".$conn->error;
}
}
$conn->close();
?>
Please check this code whether there is error in my code or why its returning this error
PHP functions can be called before defining it because PHP parses the file first and then executes it. But here is the twist.
Functions that are enclosed in a conditional statement(if else) will
not be parsed. It will be only available after PHP interprets if
So, You have to move your function outside of IF block like
if(condition){
//your code
}
//Your function
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
return $data;
}
define your test_input() function outside of
if($_SERVER["REQUEST_METHOD"]=="POST"){
and your code
if($_SERVER["REQUEST_METHOD"]=="POST"){
seems miss "}"
Changes are made to the code try this. It should work fine.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Database Connected SUCCESSFULLY";
if($_SERVER["REQUEST_METHOD"]=="POST"){
//Variables initaition
$fname=$lname=$dob=$phone=$email=$postcode=$staddress=$city=$lan=$lcwi=$ptype=$mhtype="";
//Retrieving the data from the form
$fname=test_input(mysqli_real_escape_string($conn,$_POST['fname']));
$lname=test_input(mysqli_real_escape_string($conn,$_POST['lname']));
$dob=test_input(mysqli_real_escape_string($conn,$_POST['dob']));
$phone=test_input(mysqli_real_escape_string($conn,$_POST['phone']));
$email=test_input(mysqli_real_escape_string($conn,$_POST['email']));
$postcode=test_input(mysqli_real_escape_string($conn,$_POST['postcode']));
$staddress=test_input(mysqli_real_escape_string($conn,$_POST['staddress']));
$city=test_input(mysqli_real_escape_string($conn,$_POST['city']));
$lan=test_input(mysqli_real_escape_string($conn,$_POST['lan']));
$lcwi=test_input(mysqli_real_escape_string($conn,$_POST['lcwi']));
$ptype=test_input(mysqli_real_escape_string($conn,$_POST['ptype']));
$mhtype=test_input(mysqli_real_escape_string($conn,$_POST['mhtype']));
//sql insert
$sql="INSERT INTO cwi(fname, lname, dob, phone, email, postcode, staddress, city, lan, lcwi, ptype, mhtype) VALUES('$fname','$lname','$dob','$phone','$email','$postcode','$staddress','$city','$lan','$lcwi','$ptype','$mhtype')";
if($conn->query($sql)===TRUE){
echo "<center>RECORDS UPDATED SUCCESSFULLY</center>";
}else{
echo "Error: ".$sql."<br>".$conn->error;
}
}
$conn->close();
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
return $data;
}
?>

PHP error from bind param [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I'm new to PHP but here's my code, and I'm getting :
Fatal error: Uncaught Error: Call to a member function bindParam() on boolean
I have tested and test, not sure what is going wrong, some pointers would really help to move on - thanks in advance.
$url_slot = parse_url($str);
$urlArray = explode('/',$url_slot['path']);
$passid = $urlArray['11']; // serial no
$deviceId = $urlArray['8'];
$passtype = $urlArray['10'];
$servername = "host";
$username = "user";
$password = "******";
$dbname = "db";
try {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES
(:device_id,:pass_id,:pass_type,:created,:modified)");
$stmt->bindParam(':device_id',$device_id);
$stmt->bindParam(':pass_id',$pass_id);
$stmt->bindParam(':pass_type',$pass_type);
$device_id = $deviceId;
$pass_id = $passid;
$pass_type = $passtype;
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO Devices (push_token) VALUES
(:push_token)");
$stmt->bindParam(':push_token',$push_token);
$push_token = $content['pushToken'];
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any help would be great.
Whenever you get a Fatal error for sending the wrong type to a function, print the arguments you are trying to pass on the guilty line.
Whenever the wrong type in question is a boolean, check if you wrote tests for every function return that could hurt your program if the function had failed, because a variable that contains a boolean when it shouldn't usually does because the function that gave you that value failed and returned false.
In your case, it's even more simple : The error doesn't tell you that you try to pass a boolean to a function that awaits another type, it tells you that you try to call the method bind_param(), which means that you treat a boolean as an object.
$stmt->bindParam(':device_id',$device_id);
Therefore, it is $stmt which is empty.
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES (:device_id,:pass_id,:pass_type,:created,:modified)");
The function that returns you the value you assign to $stmt being that one, I advise you to test if $stmt is different from false right after setting it, and to print the error type and message from $conn if it isn't.
In addition to that, I get the feeling that you aren't yet accustomed to work with API, you seem to lack some experience and are also trying to use PDO exceptions while working with MySQLi. Maybe you should spend some time reading their respective docmuentations.
Stack Overflow is also filled with various questions and docs regarding both.

Fatal Error Call To a member Function query()

I've seen some of the previous posts on here but they really don't explain what it is I'm looking for. maybe someone can point me in the right direction.
All I'm doing is a simple select statement that works on some other pages but not this one.
at the top of my page, I have the connection to my db: include 'myDBconnection.php'; just like any other page that uses it.
I'm using these to tell me what errors I have:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
and they are returning this:
"Fatal error: Call to a member function query() on a non-object in /var/www/vhosts/mydomainname.com/httpdocs/somedirectory/index.php on line 16"
So, this is my simple select statement that I'm trying to just display on the page:
<?php
//just a simple select statement
if($row = $con->query("SELECT * FROM ErrorCodeTable WHERE ErrorCodeID = 100"))//this is line 16 in my code
{
$eCodeId = $row['ErrorCodeID'];
$eCode = $row['ErrorCode'];
echo $eCodeId." = ".$eCode;
}
?>
So, I'm stumped. Why is it telling me that?
Just for clarity's sake, this is my DB connection and I'm reading from an INI file.
function getConnected()
{
$file = "../myConnection.ini";
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$host = $settings['connection']['default_host'];
$user = $settings['connection']['default_user'];
$paass = $settings['connection']['default_pw'];
$dbName = $settings['connection']['default_db'];
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
return $con;
}
//MYSQLI CONNECTION
$con = getConnected();
//CONNECTION CHECK
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
So, why do I get the "Fatal Error" message? Did I overlook or forget something in my query?
Be gentle. :-)
Remove the single quotes around the below statement
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
^ ^
By enclosing it in single quotes , your $con behaves like a string instead of a connection resource. The mysqli_connect function will never be executed.
Simply rewrite it like..
$con = mysqli_connect($host,$user,$paass,$dbName);

Categories