How to connect php application to database - php

I have created register form using php and validation done by using jquery.
I have files are index.php, submit.php and functions.php.
So i need to create config.php to connect database.
I have done to create table in phpmyadmin and created config.php.
Here is my config.php:
<?php
// configuration
$dbhost = "localhost";
$dbname = "crop";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "INSERT INTO crop (fname,lname,email,pass,phone,img,sex-select,dob) VALUES (:sas,:asas,:asafs)";
$q = $conn->prepare($sql);
?>
I am not sure this code correct or not? And i don't know how to include in existing my php files.
I am new to php and now i am learning, can you please help me out to fix this?
Thanks in advance.

To include the connection in other files you simply need to add the following near the top of the other file, before you need any database connection:
require_once 'config.php';
require generates a fatal error if the file is not found and require_once guarantees that the file will only be included once even though you call it multiple times. Since your application will probably not work without a database connection you want the fatal error to let you know that the file wasn't found and it's highly unlikely that you'll want more than one database connection.
There are also include and include_once but in this case you'll want to avoid these because they don't stop the script if the config file isn't found.
PHP documentation:
http://php.net/manual/en/function.require-once.php
http://php.net/manual/en/function.include.php

You have to print the results of the query that you ran.
Check Here on PDO: Prepared Statement

Try this connection code in your web application, your config.php look like
<?php
$Db_host = "localhost";
$Db_user = "root"; //DB User name
$Db_name = "crop"; //DB name
$Db_password = ""; //DB password if you have
$cnn=mysql_pconnect($Db_host,$Db_user,$Db_password) or die(mysql_error());
?>
and after that you can call this file with the help of include or require function in your page.
your submit.php looks like this
<?php require_once('config.php'); ?>

Related

PHP Prevent multiple MySQL Connections

I have a large procedural style php/mysql website, which is splitted into many different files. Within each file, i include my dbconn.php, to ensure, that a db connection is available.
It looks something likes this:
index.php
<?php
include_once ('header.php');
include_once ('nav.php');
include_once ('content.php');
include_once ('sidebar.php');
include_once ('footer.php');
?>
and within each of these files i call several other files via include_once. So in total i come up with about 30 different files.
Every file starts with:
include_once($_SERVER['DOCUMENT_ROOT'].'/dbconn.php');
Since i'm using include_once, dbconn.php should not be loaded more then once, but recently i get following php warning.
PHP Warning: mysqli_connect(): (HY000/1226): User 'username' has exceeded the 'max_user_connections' resource (current value: 20) in /var/www/html/dbconn.php on line 10
My dbconn.php looks like this:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$db = "dbname";
if(!mysqli_thread_id($con)){
$con = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($con, 'utf8');
}
unset($host,$user,$pass,$db);
?>
So there is a double check.
If there already is an open mysql connection, the file should do basicly nothing.
What am i doing wrong?
Why do i get this php warning and how do i reduce the amount of mysql connections?
Basically, it's not different calls from a single page that is leading to the problem. It's the fact that you have multiple OPEN connections at the moment.
Make sure you close you connections after they have served their purpose.
Also, try to avoid the kind of structure you currently have, have all the DB related stuff included in one file and then include it only once on your page.
I solved the problem by using a singleton pattern.
So i changed the mysqli prodecural code into mysqli objectoriented.
i got the pattern here:
http://www.davecomeau.net/blog/1/Single+Database+Object+in+PHP+5+Using+the+Singleton+Pattern

include() function in php is not working

i'm currently working on a website that has three folders namely admin,images and includes.
The includes section has the file 'connect.php' that tells about my database and the code for that is as follows..
<?php
$db_username ="root";
$db_password ="*****";
$db_host ="localhost";
$db_name= "ecommerce";
$db=mysqli_connect($db_host,$db_username,$db_password,$db_name) or die("something went
wrong");
if(!$db)
{
echo "failed".mysqli_error();
}
echo "succesfull";
?>
i just want to include this file to "dum.php" which is present in the folder admin,for which i have written the includes function.here is the code for "dum.php"
<?php include_once('includes/connect.php');?>
so,when i'm running it on browser,it has to print either "an sql failure" or a "succesful" message. but it does neither of that?
Any help would be highly appreciated
If includes is at the same level as admin, it should be:
include_once('../includes/connect.php');
You should probably use require instead of include so you get an error immediately if it fails.

host is not allowed to connect to this server

quick mysql question.
I'm new at php/mysql and followed a tutorial(php/mysql for dummies) so I don't really know what I did wrong or if the tutorial is wrong.
I have a file, "database_connections.inc", that looks like this:
<?php
$user = "username";
$host = "host";
$password = "password";
$database = "database";
?>
With the actual credentials not included for obvious reasons.
Then in another file, login.php, I have:
include("database_connections.inc");
$cxn = mysqli_connect($host,$user,$password,$database)
or die("Query died: Couldnt connect to server.");
I get an error message with the "or die" text, accompanied by a warning:
host xxxxx.000webhost.com is not allowed to connect to this mysql server in....
Why not? I'm sure my credentials are all correct.
I've read in a few places to run some shell statements...but can't really do that, I'm on Windows.
I'm using phpMyAdmin, so hopefully I can do something from there?
Open "database_connections.inc" and change it to look like this:
<?php
$user = "root";
$host = "localhost";
$password = "";
$database = "test";
?>
MySQL is by default configured to work with localhost (or 127.0.0.1), in order to allow "host xxxxx.000webhost.com" as host, open phpMyAdmin and select "SQL" and execute this query;
GRANT ALL ON your_database_name.* TO your_user#your_host_xx.xxx.xx.xx IDENTIFIED BY 'your_password';
Go into PHPMyAdmin, and edit your user.
Under Login Information, there should be an option for "Host"- try adding xxxxx.000webhost.com.

2 require_once On Same File Create MySQL Connect Issue

I have this index.php :
<?php
require_once ('required1.php');
require_once ('required2.php');
--- some mysqli_query here ---
?>
what's inside that required1.php is this :
<?php
$DbServer = 'localhost';
$DbUser = 'username';
$DbPassword = 'password';
$DbName = 'dbname';
$con = mysqli_connect($DbServer, $DbUser, $DbPassword, $DbName);
?>
and this is required2.php :
<?php
require_once 'required1.php';
--- some mysqli_query here ---
mysqli_close($con);
?>
the mysqli_close($con); on required2.php makes mysqli_query on index.php failed because the mysql connection already closed by required2.php.
how to make required2.php works independently? I mean, what ever happen on that file (required2.php) leave it there. don't bring anything into other file who calls it, specially the mysqli_close($con);
is it possible with require_once? or PHP have another function to make it like that? thanks!
Use a different connection in require2.php or don't close it. You can also include it at the bottom.
Using mysqli_close($con); in required2.php closes the connection, so after any include of required2.php, $con won't be available.
If you want required2.php to be independent, you have to use another database connection, not $con.
First of all, there is really no need to close the connection in your included file (there may be very specific exceptions...).
If you want to use your second include independently, you should refactor it to OOP. If it is a class that gets its database connection injected via its constructor (dependency injection), it would only show its name to the rest of your code so things that happen in the class or an object, would not affect the rest of your code.
Of course you still should not close your connection as that object will likely be passed around by reference but using objects / classes instead of procedural code will make it more independent an reusable.
if required2.php has nothing to do with your current script, but all you need to do is to run the script as you mentioned, i feel you can call the file required2.php using file(). this will run both the scripts separately and even if you close connection in required2.php it does not effect the current script.

Connecting to database via php code

I am programming a game in PHP and have the following code to connect to a database
//$sqldb=mysql_connect('godaddy.hostedresource.com', 'godaddyUserName', 'godaddyPassword') OR die ('Unable to connect to database! Please try again later.');
$sqldb=mysql_connect('localhost', 'root', 'mypassword') OR die ('Unable to connect to database! Please try again later.');
The trick here is that if I am on the production server I comment out the godaddy database; when I upload the code to the server I then comment out the localhost code instead.
Unfortunately the ineveitable has happened and I uploaded the code with the wrong connection commented out; this led to 24 hours of locked out customers! :(
Is there a way to have the code to tell if it is on the localhost server, and if it isn't it then looks for the godaddy connection?
you can try this to identify if its on live or localhost
if($_SERVER["SERVER_NAME"] == "localhost"
&&
$_SERVER["SERVER_ADDR"] == "127.0.0.1"){
// in localhost
$hostname = "localhost";
$username = "localuser";
$password = "localpassword";
}else{
// not in localhost
$hostname = "livehost";
$username = "liveuser";
$password = "livepassword";
}
and fail if couldn't connect to database but save the error into a file.
if(!mysql_connect($hostname,$username,$password)){
file_put_contents("mysql_connect.error",mysql_error(),FILE_APPEND);
die("Couldn't connect to database");
}
a suggestion, try not to use mysql_* anymore, switch to PDO or mysqli ..
if ($_SERVER['SERVER_NAME'] == 'the.name.of.your.devel.server') {
$host = 'localhost';
} else {
$host = 'name.of.godaddy.server';
}
$sqldb = mysql_connect($host, ....);
i normally use a method of obtaining the URL / domain of the site? This can work in certain situations and setups. Otherwise if your operating with a fixed IP than you can also use this method
Have a look over the methods using $_SERVER
PHP $_SERVER
One way would be for you to check your external IP address and see where you are. A solution should present itself by looking at the properties inside the $_SERVER global variable.
I have a good suggestion : You coding a game , game is a big program, you don't use mysql* function directly in big program , because yourself should handling them, such as error handling.i suggest you use a DB-Handler. please google for : DB-Handler PHP
As has been mentioned by other people, you can obtain the current site your script is running on using the $_SERVER variable. However, I would like to provide an alternative solution.
You could make a folder in your website (both local and production), something like config, then store a configuration file in it, for example config.php, with the following:
<?php
// Local
$db_host = 'localhost';
$db_username = 'root';
$db_password = 'mypassword';
?>
And for production:
<?php
// Production
$db_host = 'godaddy.hostedresource.com';
$db_username = 'godaddyUserName';
$db_password = 'godaddyPassword';
?>
and disallow access to the directory with a .htaccess file in the directory, something like:
deny from all
Then, in your PHP code, do the following:
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/config/config.php");
$sqldb=mysql_connect($db_host, $db_username, $db_password) OR die ('Unable to connect to database! Please try again later.');
?>
Now, simply leave the different configuration files where they're at and upload everything else, so your code will access different configuration files whenever it runs.
Also, the .htaccess file should prevent anyone from accessing the file via HTTP, and having the file contents in PHP tags, as well as a .php extension should prevent anyone from seeing any contents if they were able to access the file (PHP would parse the file before it is rendered, and would output nothing).

Categories