Open DB Connection within PHP Function - php

I wrote an addon module for our WHMCS billing system a long time ago that we recently realized was causing some issues. Essentially each module's PHP file is loaded regardless if it is actually used or not, where this is how their "hook" system is setup.
When I wrote the module, I included my "db_config.php" file at the top in the global space, which I now realize is causing this database to load every page and is apparently being written to when it shouldn't be. As this is the case, I would like to open the Database connection at the top of the function and close it at the end of the function.
I've never seen this done before nor can I find much information on it. The contents of my db_config.php appear as follows and I am wondering if I can just include_once() inside of the function?
<?php
// Connection's Parameters
$hostname = "xxx.xxx.xxx.xxx";
$database = "database";
$username = "username";
$password = "password";
// Connection
$tca_conn = mysql_connect($hostname, $username, $password);
if(!$tca_conn)
{
die('Cannot Establish Connection to Database : ' . mysql_error());
}
$tca_db = mysql_select_db($database, $tca_conn);
if (!$tca_db)
{
die ('Cannot Select Database : ' . mysql_error());
}
?>

Try this one.It might work for you.
$tca_db = mysql_select_db($database);
instead of
$tca_db = mysql_select_db($database, $tca_conn);

Related

Access denied or blank page with mysqli but not mysql

I've looked through StackOverflow for an answer to this and have so far come up empty handed. I know some have had a similar issue, but so far none of the responses to the issues have worked.
So I work on two sites, both of which are on the same host with the same PHP Admin set up (different accounts and domains, sites are not affiliated). One of them uses MySqli perfectly, without issues, while the other either gives a database selection failure, localhost access denied with password as "NO" or a blank page when I attempt to replace the MySql with MySqli.
The deprecated code:
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = #mysql_connect($host,$usr,$pwd);
if(!$connection){
die("No connection.");
}
mysql_select_db($dbname,$connection);
The MySqli I am attempting (identical to the site that MySqli works perfectly on):
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = mysqli_connect($host,$usr,$pwd);
if (!$connection) {
die("No connection.");
}
$db_select = mysqli_select_db($connection, $dbname);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
So the PHP error codes did not work at all and it had nothing to do with the local host or port, so I first checked to make sure mysqli_connect was on. Next, I ran a simple test where I echoed a random word before each mysqli command.
echo 'Passed.';
global $c_mysqli;
$conn = new mysqli($host, $usr, $pwd, $dbname);
echo '<br>Passed global mysqli.';
I found that my second pass was not working, and then proceeded to do an error message. An error showed up then. However, nothing I did fixed the issue... then I realized that one of my files, the header file, is the meat and potatoes and if it were to fail then everything else would fail too.
Sure enough, one of my lines of code contained a mysql connection and not mysqli. Long story short, double check and triple check to make sure that all
$statement = mysql_query("STATEMENT");
$query = mysql_fetch_array($statement);
Appear as
$statement = $conn->query("STATEMENT");
$query = mysqli_fetch_array($statement);

how to connect php with mysql

I am very new to php. I am trying to make a sign up page with php. So simple but I can't. I've searched across google how to connect it. They said below.
<?PHP
$user_name = "root";
$password = "";
$database = "user";
$server = "127.0.0.1";
mysql_connect($server, $user_name, $password);
print "Connection to the Server opened";
?>
I've successfully created my user database with full set of data in phpmyadmin. And running Apache and Mysql in control panel. I set the password in phpmyadmin and I changed it in $password="mypassword";. But there is no print on my web page. I think the above code is correct and I am having problems before this state. Such as the location of my database, I don't where to put it or just created on myadmin is fine. Thank you for reading my problem and kindly advice me for the beginner course.
<?php
$user_name = "root";
$password = "";
$database = "user";
$server = "127.0.0.1";
// Create connection
$con=mysqli_connect($server, $user_name, $password, $database );
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Try mysqli instead of mysql and here is why
no no . . sorry . My html path . . on desktop
PHP, in this context, is a server side programming language. You must request the script from a server that will pass it through a PHP interpreter before sending it to the browser.
Type http://localhost/etc/etc into the browser's address bar. Don't open the PHP program directly in your browser (e.g. by double clicking the file in Windows Explorer).
If you are going to use procedural style function calls with the mysqli interface:
$con = mysqli_connect('localhost','myuser','mypassword','mydb')
or die("Error " . mysqli_error($con));
If you are going to use object oriented style with mysqli interface:
$mysqli = new mysqli('localhost', 'myuser', 'mypassword', 'mydb');
Reference: http://php.net/manual/en/mysqli.construct.php
If you are going to use PDO interface
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $user, $pass);
Reference: http://php.net/manual/en/pdo.connections.php

mysqli_connect() expects parameter 1 to be string, array given

I have an issue with mysqli_connect expecting the parameter to be a string and apparently an array is given
I have a php file that writes the mysqli_connect information to a file from variables "userconnection.txt"
'localhost','root','','forum'
Then I have a standard php connection.php file with the added userconnection.txt file for the host user and password.
<?php
$connectionlink = file('userconnection.txt');
$connection = mysqli_connect($connectionlink);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
It spits out the error:
Warning: mysqli_connect() expects parameter 1 to be string, array given in /Applications/XAMPP/xamppfiles/htdocs/forum/install files/connection.php on line 4
Connect Error:
This will not work and is actually a security risk.
Security
The txt file might be accessibe from your website via some URL. An attacker who know that URL (not difficult at all) can get the file and now has your login credentials.
Save the file outside your webroot or change it's extension and contents so they arent publcly avaiable. maybe a PHP file?
Error
You have two problems. First one is that file returns all lines of the file as individual lines and not as one string. Use file_get_contents instead.
Anyways, if you do this, you will still have all three parameters in one single variable of type string. But the mysqli_connect function needs three seperate variables and not one. You can fix this with a explode.
Quick and dirty Solution
$filecontents = file_get_contents('userconnection.txt');
$connectionvars = explode("," $filecontents);
$connection = mysqli_connect($connectionvars[0], $connectionvars[1], $connectionvars[2]);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
Better but more complex solution
Create a PHP file with your connection variables:
<?php
$DBHost = "host";
$DBUser = "user";
$DBPass = "pass";
change your connection file to this:
<?php
require("connectionsettings.php");
$connection = mysqli_connect($DBHost, $DBUser, $DBPass);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
Because file functions return value is an array. Say var_dump($connectionlink);
That is much more better, if you store your parameters in variables or in constants. Use .php instead .txt, and include that file.
For example:
include('connection.php');
$link = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Error " . mysqli_error($link));
and in your connection.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password of the user');
define('DB_NAME', 'name of your database');
The problem is in line with $connection = mysqli_connect($connectionlink). Because variable isn't a string (In this case it's '$connectionlink'), so it shows the error.
In my situation I changed it to $connection = mysqli_query($connectionlink) and it solve everything.

Database code is not connecting in chat program using php

<?php
// MySQL database connection file
$SERVER = "127.0.0.1"; // MySQL SERVER
$USER = "root"; // MySQL USER
$PASSWORD = "admin"; // MySQL PASSWORD
$link = #mysql_connect($SERVER,$USER,$PASSWORD);
$db = mysql_select_db("website");
?>
This is a database connecting code for chat program but it not connecting,Can any one pls help me to correct this code?
Drop the # infront of mysql_connect, it's used to suppress error which you don't want.
Also you need to check the return value of mysql_connect which is there in $link and make sure that it is not false before you proceed and to a DB select. Calling the function mysql_error when an error occurs gives you the reason for the error.
$link = mysql_connect($SERVER,$USER,$PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}

PHP ignoring mysql_connect requests

I'm new to PHP and have installed on Linux to boot (also a newbie).
Anyway, PHP is working...
<?
$myVar = "test";
echo($myVar);
?>
... works just fine.
But...
<?
$dbhost = "localhost";
$dbuser = "myuser";
$dbpass = "mypass";
$dbname = "mydb";
echo($dbhost . "-" . $dbuser . "-" . $dbpass . "-" . $dbname);
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");
print $conn;
mysql_close($conn);
phpInfo();
?>
... does nothing. Nor errors, nothing. Its as if the code isn't even there.
Any help?
Try to do the following:
First make sure display_errors is turned on in your php configuration file. Also set the level of error_reporting to show all errors, including strict (error_reporting = E_ALL|E_STRICT). After you make changes, restart your webserver.
Run phpinfo(), and check that the mysql extension is installed and working. If it isn't make sure that you uncommented it in the php configuration file (again, remember to restart apache after each change to the configuration file).
At this point MySQL should be loaded and working, and you should be able to tell from the error (if it persists) what's the problem.
Try also dumping the contents of the connection result ($conn) to see what it contains.
In general, I'd recommend using long php tags (<?php and not <?) since it is more portable (short tags are off by default in PHP 5 installations).
Try adding this to the top of your code:
error_reporting(E_ALL);
If it does nothing, doesn't that mean that it connected fine? What output do you expect out of that statement?
You could try
error_reporting(E_ALL);
$conn = mysql_connect("localhost", "myusername", "mypassword");
if(!$conn) {
echo 'Unable to connect';
} else {
echo 'Connected to database';
}
var_dump($conn);
edit: Addressing the comment saying that you have a mysql query setup, if you are not seeing "success" it means something is wrong with your query. Add to the above
$sth = mysql_query("SELECT * FROM tablename");
if(!$sth) {
echo 'unable to query: ' . mysql_error();
} else {
echo 'success';
}
Is there more code than you're showing us? The block you have just sets up a connection. You won't see anything at all if it succeeds, you have to use $conn to do something.
To confirm, try changing your password to a deliberately wrong value, and then see if you get an error. If you do, the code works just fine.
Connecting to a database with
$conn = mysql_connect("localhost", "myusername", "mypassword") or die("Unable to connect");
will have no (visible( results if the connection was made succesfully. However, once you run this statement, you can use the other mysql functions to make make queries to the database.
Connecting to a database tells your program "hey, I want to talk to this database".
This code is supposed to create a db connection, nothing else. What do you expect to see?
Try this
<?php
$conn = mysql_connect("localhost", "myusername", "mypassword")
or die("Unable to connect");
print("code sample");
print $conn;
?>
It should print you something like "resource #1"...
And then you may use that connection to communicate with db server

Categories