creating a separate file to connect to mysql with php - php

I want to use a single file for my php application to connect to a database when the user register for the first time or login in
what is the code is it same as below is good:
$username="root";
$password="root";
$database="test";
function Save($name)
{
global $username;
global $password;
global $database;
$link = mysql_connect('localhost', $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO test (name)" .
"VALUES ('" . $name . "')";
mysql_query($query);
mysql_close();
}
Also, how can i do the require for that file? it is located in the root of the application folder should but i back slash first after require '/filename.php' or should i put double dots first?

If the file is in the same directory, you could simply use: include_once "db.php";
If it is in parent directory(ie, one level up), then use: include_once "../db.php";
Another one is to append the global DOCUMENT_ROOT with the filename(like others have given examples below).
And also, avoid mysql_* functions. Use PDO or mysqli instead.
Wish you good luck. :)

Your question essentailly boils down to "how can I include a file that is in the root from anywhere". Well, there's two answers.
The first answer is to just use inlude($_SERVER['DOCUMENT_ROOT']."/connect.php");, but that's a lot to type, especially if you have a lot of includes.
Personally, I like to start my script with chdir($_SERVER['DOCUMENT_ROOT']); Then I don't have to worry about where I am anymore - I will always be in the root folder.

Probably it is not good that you open mysql connection on every save, if there will be many such calls per request.
inlude($_SERVER['DOCUMENT_ROOT'] . '/db.php');

A few comments:
First, if you don't need to use the password and username and database elsewhere, you should just define them in the function.
Second, If I'm not mistaken if you put the "/" in front of the path that will take you all the way down to the root of the filesystem, which I'm guessing this user wouldn't have access to. That being said, I would use ".." to navigate up the hierarchy. So use:
require_once("../path/to/file.php")

Rather that putting the include file in the document root, you should create a directory for common include files, and add it to the include_path setting in php.ini. Then you can just do include 'connect.php';.

Related

How do I use mysqli in an included file when the mysqli connection is stored in another included file?

I'm about to use mysqli instead of mysql for the first time in my procedural PHP application.
index.php
include(db_conn.php);
<html>
<body>
<?php include(content.php);?>
</body>
</html
db_conn.php
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
content.php
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
# more code...
mysqli_query necessarily requires the connection variable and my connection is stored in variable $con in the included db_conn.php file which is unavailable in another included content.php file.
Within your content.php use require(db_conn.php); And if you have a function defined in there, you're going to have to put require(db_conn.php); INSIDE that function.
The database connection doesn't seem to have exactly the same scoping as a standard variable.
I know when coding it, you feel like "I should only have to include this once!" but shrug get everything else working first, and if someone wants to pay you to go back and try to "fix" this... work on it then. ;)

Having Problems With PHP Connection

This is the code that connects to my SQL database. I'm new with this stuff and it seems to be semi-working but certain features on my website still don't work.
<?php
$con = mysql_connect("localhost","username","password");
$select_db = mysql_select_db('database1',$con);
/*$con = mysql_connect("localhost","username2","password2");
$select_db = mysql_select_db('database2',$con);*/
?>
This is the site in question: http://tmatube.com keep in mind the credentials above are filled in with what the programmer used for testing on his own server... ;) unfortunately I don't have access to him for support anymore.
Anyway, here's my thoughts on how this code needs to be edited maybe someone can chime in and let me know if I'm correct in my assumptions:
<?php
$con = mysql_connect("localhost","username1","password1"); -------------<<< leave this line
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);
/*$con = mysql_connect("localhost","DB_USERNAME_HERE","DB_PASSWORD_HERE");
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);*/
?>
Ok - now on to a few problems I noticed...
What does this do? /* code here */? It doesn't work at all if I leave that bit in.
Why is it connecting to database twice? and is it two separate databases?
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con); <<<---- single '
When I tried to see if that line was correct the examples I saw had quotes like this
$select_db = mysql_select_db("DATABASE_NAME_HERE",$con); <<<---- double "
Which one is right?
He didn't leave it out. What he did was leave the database to be connected using the root, which has no password. The other connection (which is commented out) is using another user, rajvivya_video, with a password defined.
In testing it MIGHT be okay to connect to root and leave it without password, but even that is not recommended, since its so easy to work with a user and password defined (besides root).
Here is php mysql connect with mysqli:
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
?>
No difference here with ' or ". (Anyway use mysqli and you can the wanted db as 4th parameter.) php quotes
/* comment */ is a commented out so the php does not care what is inside so only 2 first rows of are affecting (they are same mysql database on the local machine and 2 different user + password combinations). Comment in general are used to explain the code or removing part of the code with out erasing it. php commenting

Document Root; Login Variables

I recently posted a question here; however, in the great answers that I got, I was told that my connection queries were unsafe and deprecated.
$con = mysql_connect("localhost", "userX", "passX") or die('Could not connect to server');
mysql_select_db("dbX", $con) or die('Could not connect to database');
$query="SELECT fieldX,filedX2 FROM tableX WHERE varX";
$result=mysql_query($query);
while($row=mysql_fetch_array($result,MYSQL_ASSOC))
Apparently, the material from which I learned is old. So I looked into this issue and came across these two items:
1."In real practice, it would be best to place username and password in a folder out of the Apache Web server's path so it's not accessible via the Web."
2."Put username and password in a file that is not in the document root of the web application"
<?php
include("connection.php");
$link = mysql_connect($connection_server, $connection_user,$connection_password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
-----
/* --- Connection Variables ---*/
$connnection_server = "[server]";
$connection_database = "[db]";
$connection_user = "[username]";
$connection_password = "[password]";
I know this might sound like a dumb question (obviously, I'm a newbie), but what is the document root? What does "outside the document root" and "out of the Apache Web server" mean?
For now, as I'm learning, I'mv just on MAMP, but when I do go on a commercial server, say Godaddy's, what what would that mean?
Also, I'm assuming
$connnection_server = "[server]";
$connection_database = "[db]";
$connection_user = "[username]";
$connection_password = "[password]";
in the example above means that these variable are on a separate file (e.g., connection_var.php), correct?
Thanks in advance for your knowledge and help.
Jen
The document root is the highest directory (top level) that a browser can directly request files or pages from. Take for example:
http://example.com/index.php
index.php is in the document root. There is no higher level that the browser can request.
http://example.com/images/mrcode.jpg
mrcode.jpg is not in the document root because it resides in the images directory.
What does "outside the document root" and "out of the Apache Web server" mean?
Outside of the document root refers to files that are stored above this directory and therefore cannot be directly requested by a browser. For example your directory structure may look like:
/websites/example.com/public_html/index.php
If you were to store your database credentials in:
/websites/example.com/dbdetails.php
This would be out of (or above) the document root. Storing connection credentials inside the document root is not considered a vulnerability, however storing them outside can be slightly better. PHP can still access files above the document root (assuming you have permission). Shared hosts typically give you access to one level above the document root.
Your immediate problem is that you're using the deprecated mysql_* library. The problem with this is it is being removed from newer versions of PHP and so if you continue to use it, your applications will eventually become completely unusable. The MySQLi and PDO libraries also offer Prepared Statements which should be used instead of the escaping methods to prevent SQL Injection because they offer greater security. See here for a good PDO tutorial. If you were told your queries are unsafe then they probably contain SQL Injection vulnerabilities.

The mysqli_connect not working

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

PHP define() doesn't seem to be working with include()

I've been trying my hand at OO PHP, and currently have three files. I have a class_lib.php which, at the moment, just has a databaseServer class, an index.php file and a definitions.php file. I want to put all my sensitive database info into the definitions file. However, when I do, I get an error when trying to connect to the database: "Unkown server DB_HOST". My definitions file is:
<?php
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PASS","password");
define("DB_NAME","database");
?>
Then I use them in the index file like so:
include('definitions.php');
include('class_lib.php');
$testing = new databaseServer();
$testing->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
And the function I use in the databaseServer class is this:
function connect($host,$user,$pw,$db) {
$this->con = mysql_connect($host,$user,$pw);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
$this->selectDb($db);
}
function selectDb($database) {
$this->db = mysql_select_db($database,$this->con);
if (!$this->db) {
echo "Could not Select database: " . mysql_error();
}
}
Any ideas why this would not work? I've also tried putting the definitions file into an include in the class_lib file, but it still doesn't work.
This should work fine, and I've never seen it not work.
Make 100% sure the includes are in the correct order (the defines need to be loaded first)
Make test outputs of the constant values in the "definitions.php" file and the index file
Make 100% sure you are calling the right files
Please check if your server supports short_open_tag this value would be commented.
I just enabled it with on and it started working.
call it config.php
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
?>
then include("config.php"); on your pages
working
<?php
define('KLINGON_SEPARATOR', '');
?>
not working
<?php
define('KLINGON_SEPARATOR', '');
silly... IDEA says "redundant closing tag"
You just need to take out the define functions of the destinations file and transfer it to the source file (in your case "translation.php") and ready to work!
Like this the bug with define functions on receiving string params do not happen and you will include the CONSTANTS implemented already.
I faced this trouble and found myself just this one solution.
I had a similar issue today and it seems to possibly be an invalid character code at the end of the file. I found this on stack PHP define is not registering constants His solution (removing extra spaces) worked for me.
The key in this is using the constant() function to pull the value from the defined constants:
echo constant("DB_USERNAME");

Categories