Global Scope fails for included file - php

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.

Related

Php connecting but failing to select a database

I am having trouble getting php to connect to my mysql database on a shared hosting. This worked when it was on my MAMP local server.
I get the following error:
Error: No database selected Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /hermes/bosnaweb03b/b2270/ipg.theburguersaredownco/cheval/main.php on line 34
My db_connect php file:
<?php
$connect = mysqli_connect('theburguersaredownco.ipagemysql.com', 'user', 'password');
if (!$connect) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_select_db('db_cheval');
?>
I get the message: "Connected successfully", so I am assuming the connection to the database is established and therefore there are no issues with the mysql_connect function or any of its arguments (i.e. the user and password are correct etc...).
my main.php file:
<?php
include 'db_connect.php';
include 'header.php';
error_reporting( E_ALL );
ini_set( "display_errors", 1 );
?>
<a id="roundLogo" href="index.php" class="not-active"></a><div>
</div></a>
<div id="subheader" class="notVisible">
<nav id="menu2">
<ul>
<?php
$query = mysqli_query($connect,"SELECT * FROM categories");
if (!$query) {
printf("Error: %s\n", mysqli_error($connect));
// exit();
}
while ($q = mysqli_fetch_array($query)) {
if($q['id']<4){ ?>
etc...
Line 34 is this one:
while ($q = mysqli_fetch_array($query)) {
It is the first time I do this and I am new to php and mysql so I don't have much experience. Can someone help me find the problem here. How can I debug this?
Thank you
You should use localhost for host parameter even if you running on hosting or local webserver but your problem is missing parameter in mysqli_select_db that why "No database selected" return
$connect=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($connect,"db_cheval");

How do I start a PGSQL connection in PHP?

I am trying to start a pgsql connection in php but i get pg_last_error(): No PostgreSQL link opened yet Please forgive my amateur question as i am a bit new to php.
Here is my php code:
<?php
$connect = pg_connect("host=xxx.xx.xxx.21 dbname=d106 user=b16 password=bran") or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
In your pgsql connection you have missed the port number.
Try this way.
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" ) or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
You can store PgSQL connection code in one PHP file to reuse
pgsql_db_connection.php file
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" );
if(!$connect){
echo "Error : Unable to open database\n";
}
?>
Call pgsql_db_connection.php file in other php files to use your database connection.
<?php
require_once('pgsql_db_connection.php');
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo pg_last_error($connect);
exit;
}
while($row = pg_fetch_array($result))
{
$coor = $row[0];
echo $coor;
}
?>
When pg_connect fails, it returns FALSE and produces a PHP warning with the detailed information on why it couldn't initiate the connection. If you can see the other message:pg_last_error(): No PostgreSQL link opened yet that you're reporting, I'd expect you should be able to see the previous one too, which is the one normally telling the reason of the failure.
If the display_errors configuration setting is set to 0, the first message would not show up on the browser/screen but the second would not either.
Anyway, assuming you can't have access to pg_connect warnings for whatever reason such as custom error handler, what's wrong with your code is that pg_last_error() must have an already opened connection to work.
To access the detailed error message from a failed pg_connect, the built-in PHP function error_get_last() (returning an array) could be used.
<?
$connect= pg_connect("your-connect-string");
if (!$connect) {
print_r(error_get_last());
// for only the message:
// echo error_get_last()['message']
}
die("DB connection failed");
?>
See also how to catch pg_connect() function error? if you prefer exceptions.

PHP redirect with header not working

Here is my code:
<?php
$url = $_GET["id"];
$servername = "XXXX";
$username = "XXXX";
$password = "XXXX";
$dbname = "XXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM Table WHERE id='".$url."'";
if ($conn->query($sql) === TRUE) {
echo 'Row deleted successfully';
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
header('Location:index.php');
exit;
?>
But header redirect is not working...
Here is the error log:
Strict Standards: header(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EST/-5.0/no DST' instead in /homepages/5/d394578306/htdocs/XXXXX/XXXXXX/delete.php on line 24
Warning: Cannot modify header information - headers already sent by (output started at /homepages/5/d394578306/htdocs/XXXXX/XXXXXX/delete.php:1) in /homepages/5/d394578306/htdocs/XXXXXX/XXXXXX/delete.php on line 24
<?php
Delete the whitespace before the PHP tag - that counts as output and will stop the header() call from working.
You're also doing some echo calls, both of which will also stop the redirect from working as echo will output content/headers to the browser.
It appears to me that the timezone warning of the header causes the output, which in turn makes the function itself not work. Try doing this:
#header('Location:index.php')
The # will suppress error output for that particular function call.
Also, as Bulk correctly pointed out, you should disable your echo calls in lines 17 and 19, or move them below the header method call.
Based on the timezone error, try this:
<?php
date_default_timezone_set("--HERE YOUR TIMEZONE---");
$url = $_GET["id"];
$servername = "XXXX";
$username = "XXXX";
$password = "XXXX";
$dbname = "XXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM Table WHERE id='".$url."'";
if ($conn->query($sql) === TRUE) {
echo 'Row deleted successfully';
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
header('Location:index.php');
exit;
?>
Now replace the "--HERE YOUR TIMEZONE---".
Here you can find the correct timezone for your country: http://php.net/manual/en/timezones.php

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

PHP mysqli unexpected parameter Question

I feel like a total n00b for not understanding what I'm doing wrong, but here goes.
I'm writing a simple web form that's storing information in a MySQL database. I'm getting this error:
mysqli_stmt_init() expects parameter 1 to be mysqli, null given in /myfile.php
Here's my code:
$server = 'localhost';
$username = 'myusername';
$password = 'mypassword';
$db = 'mydb';
$link = mysqli_connect($server, $username, $password, $db);
.
.
.
$stmt = mysqli_stmt_init($link); /*This line throws the error*/
Any ideas? Thanks in advance.
Are you 100% sure you are successfully connecting to the database?
Add at the top of your script:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Also add right below your connection line:
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
If this is your dev server you should probably set the following lines in your php.ini file rather than in each script.
error_reporting = E_ALL
display_errors = on
if that doesn't solve you problem than you should print our $link to see what it is.

Categories