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

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.

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.

Using include/require to connect database [duplicate]

This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 6 years ago.
I have a following code
//dsn.php
//Object Oriented way
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
//check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
die("could not connect:".$conn->connect_error);
}
//index.php
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
$sql = "sql command";
$result = $conn->query($sql);
//not working
$conn->close();
}
This will display warning and notice that says:
Warning: mysqli::query(): Couldn't fetch mysqli
Notice: Trying to get property of non-object
Warning: mysqli::close(): Couldn't fetch mysqli
However this one works:
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
include $dsn.php
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
How do I use just one include file for DSN and use repeatedly on other functions?
EDIT
sorry I forgot to mention
function a($conn) {}
function b($conn) {}
I passed the variable $conn but it still displays the warning and notice I mentioned above
When you include a file, you can imagine that in the background it is just copy-pasting that code into the current document.
There are 2 problems with your code...
The $conn variable is not in scope inside function a or b.
Even if it was in scope and accessible, you are closing the connection after each query. A better way to do it is to open the connection, run all queries and close the connection when it is no longer needed.
The second piece of code you gave works because it is creating a new variable $conn inside of b(), but this is not ideal as it will create a new database connection every time you execute that function.
Something like this may suit your needs:
include 'dsn.php';
function a($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
function b($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
$aResult = a($conn);
$bResult = b($conn);
$conn->close();
Notice that we are only including 'dsn.php' once, and then passing around that existing connection to the functions that need it.
This is very simple. On page load, the connection file is included which makes $conn the connection object available to the remaining codes. The $conn is used by the functiona() and it is then closed at the end of the function. $conn->close(); destroys the database connection object means, $conn is no more object hence it should not be treated as object. But the Function b() is treatong it as database connection object and resulting into error.
But if you again include the connection file, inside the function b() then $conn becomes available to the function as local object. And works as it should.
Do not close the $conn() on the any function till you are dealing with DB.
function a() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function incDbConnectionFile() {
include 'dsn.php';
}

Undefined variable/empty property error after access

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

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

2 MySQL connections across 2 differents host

I have 2 connection database (MySQL) in different host like this:
//database 1
$dbhost='localhost';
$dbuser='user1';
$dbpass='pass1';
$dbname='dbname1';
//database 2
$dbhostams='192.168.16.3';
$dbuserams='user2';
$dbpassams='pass2';
$dbnameams='dbname2';
function dbconnection($dbhost,$dbuser,$dbpass,$dbname){
if(!mysql_connect($dbhost,$dbuser,$dbpass)){
echo "Error occure on opening connection or database. Period.";
}else{
if(!mysql_select_db($dbname)){
echo "Error occure on select databases !";
}
}
}
function dbconnectionams($dbhostams,$dbuserams,$dbpassams,$dbnameams){
$cxn = mysql_connect($dbhostams,$dbuserams,$dbpassams,$dbnameams);
if( $cxn === FALSE ) {
die('mysql connection error: '.mysql_error());
}else{
if( !mysql_select_db($dbnameams) ){
echo "Error occure on select databases !";
}
}
}
when i use:
dbconnection($dbhost,$dbuser,$dbpass,$dbname);
at my page code, and use:
dbconnectionams($dbhostams,$dbuserams,$dbpassams,$dbnameams);
at another line of code in same page, error occured, like this:
Warning: Access denied for user: 'apache#localhost' (Using password: NO) in
/home/firman/html/fdrsimpeg/sdm-aam/include/dbclass.php on line 17
Warning: MySQL Connection Failed: Access denied for user: 'apache#localhost'
(Using password: NO) in /home/firman/html/fdrsimpeg/sdm-aam/include/dbclass.php
on line 17
mysql connection error:
what must i do to solve this problem?
Your global variables ($dbhost, $dbuser, etc.) are not within the scope of your function calls; for example, if those function calls take place within another function, you will need to declare the variables within the function with the global keyword in order to access them (otherwise PHP thinks you're referring to different variables of the same name that are local to the function):
function foo() {
global $dbhost, $dbuser, $dbpass, $dbname;
dbconnection($dbhost,$dbuser,$dbpass,$dbname);
}
Read more on PHP variable scope.
First of all, change the variable names, it will be easier for you to read the code ... Second, the problem seems to be with the connection, as it is detecting that the username is "apache". Check the variables names in the functions ... change them and try again.
//database 1
$dbhost='localhost';
$dbuser='user1';
$dbpass='pass1';
$dbname='dbname1';
//database 2
$dbhostams='192.168.16.3';
$dbuserams='user2';
$dbpassams='pass2';
$dbnameams='dbname2';
function dbconnection($_dbhost,$_dbuser,$_dbpass,$_dbname){
if(!mysql_connect($_dbhost,$_dbuser,$_dbpass)){
echo "Error occure on opening connection or database. Period.";
}else{
if(!mysql_select_db($_dbname)){
echo "Error occure on select databases !";
}
}
}
function dbconnectionams($_dbhostams,$_dbuserams,$_dbpassams,$_dbnameams){
$cxn = mysql_connect($_dbhostams,$_dbuserams,$_dbpassams,$_dbnameams);
if( $cxn === FALSE ) {
die('mysql connection error: '.mysql_error());
}else{
if( !mysql_select_db($dbnameams) ){
echo "Error occure on select databases !";
}
}
}
You need to pass true as fourth parameter to the mysql_connect function.
$database1 = mysql_connect($host1, $user1, $pass1);
$database2 = mysql_connect($host2, $user2, $pass2, true);
mysql_select_db('database1', $database1);
mysql_select_db('database2', $database2);
And to query your database use this:
mysql_query('SELECT * FROM table', $database1);
mysql_query('SELECT * FROM table', $database2);
Check this answer here on Stackoverflow....link
I didn't see anything obviously wrong, I tested your code as provided and both connections worked.
Check to see if mysql.default_user, mysql.default_host etc. is set within your php.ini

Categories