I have db.php with the following code.
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "password";
$dbName = "test";
$databaseLink = new mysqli ($dbHost, $dbUser, $dbPass);
if($databaseLink)
{
mysqli_select_db($databaseLink,$dbName);
}
?>
which I usually import on to other php page like this
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/core/include/db.php";
?>
and works fine. I can start querying using $databaseLink. But there is one page where its not working. But if I explicitly define the connection like this $databaseLink= mysqli_connect("localhost", "root", "password", "test"); it works. There are other php files in the same directory which has no issues.
I have tried
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/core/include/db.php";
global($databaseLink);
?>
But that does not seem to work too. I have looked it up online for examples but can find any help.
you forget to require your db.php file
require_once($path);
You can simply use include at the top of your php code to link in another php page.
include '/core/include/db.php';
Related
I'm using a PHP file stored on my host to connect to a database stored on the same host, this is working fine.
I am using the below to connect to the database (example connection details)
<?php
$db = new PDO('mysql:host=localhost;dbname=myDB', 'myusername', 'mypassword');
My question is; seeing as I have specified the password (and other details) to connect to my server in my PHP file, can't someone with the direct link to my PHP file just download it and open it in a text editor to see those details?
If so, should I be passing the connection details to the php file like this:
<?php
$server = $_POST['server'];
$database = $_POST['database'];
$username = $_POST['username'];
$password = $_POST['password'];
$db = new PDO('mysql:host=$server;dbname=$database', $username, $password);
Expanding a bit on my comment, ideally you want to have this in separate files, one used for global configuration you can then import to your other modules like the example below.
Config.php file:
<?php
$HOST = 'hostname';
$DB = 'dbname';
$USER = 'username';
$PWD = 'password';
... other variables and global config ...
?>
DB Connection File:
<?php
include 'config.php';
$db = new PDO("mysql:host=$HOST;dbname=$DB", $USER, $PWD);
?>
Notice how the string inside the PDO connection is double quoted, because if single quoted, string interpolation won't work.
Your variable $server and $database are not interpreted correctly as you are using single quote '. You need to use double quote " to correctly pass variable values. (Refer for more details What is the difference between single-quoted and double-quoted strings in PHP?) Change your code as below.
<?php
$server = $_POST['server'];
$database = $_POST['database'];
$username = $_POST['username'];
$password = $_POST['password'];
// Replaced ' with "
$db = new PDO("mysql:host=$server;dbname=$database", $username, $password);
First off, I'm trying to make sure that I'm not showing my MySQL password in my index page's source code. I've determined that making a "mysql.conf" file with the information I need will be sufficient.
Here is the section of code, pre-conf file. This worked without any problems:
$dbhost = "mysql.host.com";
$dbuser = "username";
$dbpass = "password";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
Now, here is the configuration file's contents (mysql.conf):
mysql.host.com
username
password
And the corresponding changes to the code...
$dbConfig = file("./config/mysql.conf");
$dbhost = $dbConfig[0];
$dbuser = $dbConfig[1];
$dbpass = $dbConfig[2];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
However, with the changes to use the configuration file, the MySQL connection now fails, giving me this error response:
"Could not connect: Access denied for user 'username'#'chain-lightning.dreamhost.com' (using password: YES)"
What am I missing? I've triple-checked that the text in the configuration file is the same as when I used static strings. Thanks!
The error you are getting mostly because of the data getting from file is not as you think. all your value will be added with extra newline value.
from http://php.net/manual/en/function.file.php
Returns the file in an array. Each element of the array corresponds to
a line in the file, with the newline still attached.
use trim function with your variable it will work fine.
$dbConfig = file("./config/mysql.conf");
$dbhost = trim($dbConfig[0]);
$dbuser = trim($dbConfig[1]);
$dbpass = trim($dbConfig[2]);
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
or you can use FILE_IGNORE_NEW_LINES flag in file function
$dbConfig = file("./config/mysql.conf", FILE_IGNORE_NEW_LINES);
$dbhost = $dbConfig[0];
$dbuser = $dbConfig[1];
$dbpass = $dbConfig[2];
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
<?php
$phpContent = '<?php
session_start();
include("../conn.inc.php");
$id = $_SESSION["gameid"];
$select_content = mysql_query("select * from game_details where id=".$id);
$arr_content = mysql_fetch_array($select_content);
echo $arr_content["name"];exit;
?>
';
fwrite($phpFile, $phpContent);
fclose($phpFile);
?>
In this code, I am selecting the datas from the database of a particular value of id stored in $id. The code in $phpContent, I am writing it into a file,it shows this error,when I am opening that written file:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean
Can anyone say how to eliminate this error ?
conn.inc.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$db_host = "localhost";
$db_user = "root";
$db_name = "pixo";
$db_pwd = "mysql";
$connection=mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
Your issues with mysql_select_db you have forgot to pass $connection as second parameter please change your code with below code.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$db_host = "localhost";
$db_user = "root";
$db_name = "pixo";
$db_pwd = "mysql";
$connection=mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name,$connection);
?>
More About mysql_select_db
But my advice is now days mysql_select_db is not secure please go with MySQLi Functions More About Mysqli
Hope above code will helps you. you forgot pass $connection parameter.
It seems like your mysql requĂȘte is returning FALSE, var_dump your $select_content var to see what it is returning exactly.
Can any of you guys help me to reorganize this code? I'll try to explain the problem below.
I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webappeind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output gegevens van elke rij
while($row = $result->fetch_assoc()) {
echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
}
} else {
echo "0 resultaten";
}
?>
You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :
<?php
function GetMyConn() {
$server_name = "localhost";
$db_name = "db_name_goes_here";
$db_user = "user_name_goes_here";
$db_pass = "password_goes_here_muahhhaa";
$db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
$MyConn = new PDO($db_full_addr, $db_user, $db_pass);
$MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $MyConn;
}
?>
In the calling file, you would say, something like :
require_once "GetConn.php";
$MyConnHere = GetMyConn();
$SqlHere = "Sql Statemetn goes here...."
$SqlHere2 = $MyConnHere->prepare($SqlHere);
$SqlHere2->execute();
Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.
I have the following code to do a simple image upload and store a few data, however I want to remove the section(s) of the code that have the direct database username password and host, with a simple include("config.php") in the heading. So what I am asking apart from the include("config.php") line how would I make adjustments to the code example:$conn = $db->prepare($query); an so on
<?php
include("config.php");
define('UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . 'photohandling/uploads/');
define('DISPLAY_PATH', '/photohandling/uploads/');
define('MAX_FILE_SIZE', 2000000);
$permitted = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif','image/tiff');
$dames2=time();
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'password';
$db_name = 'test';
if (!empty($_POST)){
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$age=$_POST['age'];
$acquirer_bin=$_POST['acquirer_bin'];
$terminal_id=$_POST['terminal_id'];
$trace_id=$_POST['trace_id'];
// get the file extension
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myfile = $acquirer_bin.$trace_id.$dames2.$randName . '.' . $ext;
// save image path
$path = UPLOAD_PATH . $myfile;
if (in_array($fileType, $permitted) && $fileSize > 0 && $fileSize <= MAX_FILE_SIZE) {
//store image to the upload directory
$result = move_uploaded_file($tmpName, $path);
if (!$result) {
echo "Error uploading image file";
exit;
} else {
$db = new mysqli("localhost", "root", "hynes21", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s<br/>", mysqli_connect_error());
}
$query =
"INSERT INTO tester(fname,lname,age, acquirer_bin, terminal_id, trace_id,photo_name, size, type, file_path) VALUES(?,?,?,?,?,?,?,?,?,?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("ssiisisiss",$fname,$lname,$age,$acquirer_bin,$terminal_id,$trace_id, $myfile, $fileSize, $fileType, $path);
if (!$conn->execute()) {
echo 'error insert';
} else {
echo 'Success!<br/>';
echo '<img src="' . DISPLAY_PATH . $myfile . '"/>';
}
} else {
die("Error preparing Statement");
}
}
} else {
echo 'error upload file';
}
} else {
echo 'error';
}
?>
You really shouldn't define database credentials in code. A solid why to do this is to use a configuration file. PHP provides a built in function called parse_ini_file that is perfect for retrieving data from config files (in a certain format ofc).
Here is an example of a ini file that can be parsed by parse_ini_file [docs]
[db]
host = localhost
user = root
pass = password
database = test
As you can see the format of the file is very similar to the php.ini file.
Keep this db.ini file in a place that is not accessible by the web server but can be read by PHP.
Here is a function that can utilize the data in the ini file and create a new mysqli object for you.
// somefile.php
function new_db() {
$info = parse_ini_file('db.ini', true);
return new mysqli($info['db']['host'],
$info['db']['user'],
$info['db']['pass'],
$info['db']['database']);
}
To use your new_db function.
require_once 'somefile.php';
$db = new_db();
$stmt = $db->prepare($query);
// ...
If I understand correctly, you want to use the values defined in config.php. If so, this is all you need to do:
config.php
define(DB_HOST, 'localhost');
define(DB_USER, 'root');
define(DB_PASS, 'hynes21');
define(DB_NAME, 'test');
php file from where config.php is included
Option 1:
$db_host = DB_HOST;
$db_user = DB_USER;
$db_pass = DB_PASS;
$db_name = DB_NAME;
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
Option 2:
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
And yeah, a heap of ppl will tell you to use PDO instead of mysqli. Indeed you should, but that's doesn't give you an answer to your question :)
Let's say in your config.php file you have this:
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'hynes21';
$dbName = 'test';
Then in your code above you would replace this line:
$db = new mysqli("localhost", "root", "hynes21", "test");
with this:
$db = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
and the rest of your code should just work, thanks to variable scoping.
You could also put the db connection in the config.php file as well, which would allow you to destroy the stored connection info variables so they wouldn't be hanging around anywhere for accidental output:
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'hynes21';
$dbName = 'test';
$db = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
unset($dbHost);
unset($dbUser);
unset($dbPass);
unset($dbName);
This would mean every page load would have the overhead of calling mysqli(), even if that page didn't use the database. But if you have a data driven site then virtually every page will want to call mysqli() anyway so that's not such a big deal.
Later on you may want to look in to using a database wrapper so you don't have to store your DB connection in a locally scoped variable, but this approach will work just fine for simple applications.