We know that there are lots of tutorials (some official too) on the internet about PHP and MySQL connectivity. Then why am i posting it here ? i am posting because most of those articles are not simple and easy to understand and this is why we are doing it here. We assume that you have already installed XAMPP in your System and running it using XAMPP control panel.
To connect PHP to MySQL database you need to know following important things:
- Host name.
- MySQL user name.
- MySQL password.
If you have installed XAMPP in your system (not web server) then host name is localhost. By default MySQL user name and password is “root” and blank ( “” ) respectively. Let us create one simple project and try to connect our PHP code to MySQL.
If you are on Windows then there is “htdocs” folder in “C:/xampp/htdocs/” (if installed on default location). If you are on Linux (most probably Ubuntu) then it is located on “/opt/lampp/htdocs” (you should switch to root user before creating folder in it.).
In any case create any folder, lets say “test-db-connection” and create simple PHP file with following code.
$user="root";
$password="";
$con=mysql_connect($host,$user,$password);
if(!$con) {
echo '
Connected to MySQL
';} else {
echo '
MySQL Server is not connected
';}
Save it in the project folder and go to localhost/test-db-connection/filename.php and see what it is giving.
mysql_connect() is PHP inbuilt function to connect to MySQL database with the parameter shown above.
To perform SQL queries, you need to select database. You can do that using mysql_select_db(“database_name”,optional connection variable). Once Database is selected you can perform queries using mysql_query(“SQL query”). Here is sample code.
$user="root";
$password="";
$con=mysql_connect($host,$user,$password);
if(!$con) {
echo '
Connected to MySQL
';//if connected then Select Database.
$db=mysql_select_db("YOUR_DATABASE_NAME",$con);
$query=mysql_query("YOUR_MYSQL_QUERY",$db);
}
else {
echo '
MySQL Server is not connected
';}
I hope you have understood the concept. You can ask any doubt in comment.
thnx bro
Most welcome.
hi Shahid,
need help,
i have put my application onto PCF(Pivotal cloud Foundry)
i am unable to connect to mysql database,
the application logic is written in PHP language
my config file looks like below.
define(‘mysql_db_hostname’,’http://10.1.2.0/’); —>ex: ip
define(‘mysql_db_user’,’monitor’);
define(‘mysql_db_password’,’******’);
define(‘mysql_db_database’,’********’);
the socket is open and the php pages appears but unable to connect to db, please help me with what changes should i make to connect to mysql db
thanks
Please show me the code which you are using for connection string. This is just configuration.
$conn = mysql_connect(“localhost”,”primeb5_mysql”,”***”);
$db = mysql_select_db(“primeb5_unigis”);
$query = “SELECT * FROM lesson3”;
$result = mysql_query($query);
The function “mysql_query” is responsible for executing the query within the brackets on the database. But how does this function know which database to use? $conn and $db have been defined, but they are never used within the code.
Bro I think you need to use mysqli not mysql because latest version not support mysql .
Thanks for update. This tutorial was for beginners. I will update with SQLi and prepared Statement.
Thanks for the write up. Can point me to an example where you put this concept into practice?
Yes. Let’s say you are building Registration form where user will submit and their information will be store in Database , in that kind of scenario you need to connect to your database ( assuming MySQL here) in order to do further database operations.
Thanx you guys you are awesome
thanks man this helped me a lot
when i took ur code in my project. basic one of just checking whether its connected or not… it kept loading for a long time.. n didnt provide any result.
Your logic is reversed. If !$con that means your connection attempt failed.
So either write
if ($con) {
instead of
if (!$con) {
or just handle the failure first, throw an exception and then continue assuming success, like it is done in the official documentation examples here: http://php.net/manual/en/function.mysql-connect.php
In this particular case, it doesn’t make any difference whatsoever whether you use mysql_connect or mysqli_connect. The former is deprecated and will be removed at some point in the future, but as of PHP 5.5 it still works.
thankz a lot @Nicolai Czempin
Can you edit this post to be up to date with mysqli?
Yes i will.
i am unable to store data in my database can you help me?
Yes what is the issue.
its still not working
Fatal error: Call to undefined function mysql_connect() in C:\xampp2\htdocs\test\index.php on line 5
what does it mean?
what does Fatal error means?
I took ur code in my project and I got
“Warning: mysql_select_db() expects parameter 1 to be mysqli, string given in C:\xampp2\htdocs\BDPortal\admindbconf.php on line 15”
Can you help me with this?
thanks.
use mysqli instead of mysql
I got same response as tin above from the code given.
Please help because I have tried several codes and none is working.
$query=mysql_query(“YOUR_MYSQL_QUERY”,$db);
Above method has error, since the second parameter has to be a connection object not db.
Please correct.
i have try your code but not connected to the database. its just showing localhost refuse to connect.
Make sure MySQL is up.
mysql is up to date.
i have try your procedure but my database is not connecting. So what should i do.
I did try this procedure on my XAMPP but it not working .
if anyone could help me please .
i got this error in my browser.
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\conn.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\conn.php on line 5
$host=”localhost”;
$user=”root”;
$password=””;
$con=mysql_connect($host,$user,$password);
if(!$con) {
echo ‘Connected to MySQL’;
} else {
echo ‘MySQL Server is not connected’;
} anable to connect
Try chaning your host.
I’m very new to PHP, but not programming. The following code from the example would seem to read that if it is NOT connected then echo ‘Connected to MySQL’. Maybe it’s different in PHP, but in other languages the ! sign means NOT. (I’m not shouting with capital letters just trying to be clear)
—-
if(!$con) {
echo ‘Connected to MySQL’;
} else {
echo ‘MySQL Server is not connected’;
}
—-
Whatever the case, my code seems to echo “Connected to MySQL” even with a made up username. This is surely a reflection of my inexperience with PHP, but just curious how the ! operator works.
! performs the comparison with a boolean value, if it is false then ! FALSE = true i.e good case to go in if condition.
Can you please tell me how to create login form and how to check its backend in XAMPP?
m getting els part msg dt sql server is not connected…..i hv checked the code bt not able to catch the problem…plz help me….:)
Hi,
I am not able to select database only
I just wasted more than 15 hours everytime it says connection problem
Code:
$con is my connection string
$con=mysql_connect(“localhost”,”root”,””);
mysql_select_db(“test”,$con) or die(“connection problem”);
Output is connection problem
Please print $con or check if($con) { // put db select code here}
how to run in xampp server
i was created a database with name my_db and it was saved in xampp ht docs folder.
how can i run it.
Change the name of the database in the code file.
Hi…I want to know how to connect mysql with php
what is the need of blank space in the code
mysql_connect(“localhost”,”root”,” “);
Its password.
hi when i run by xampp the filename.php i have this output:
$host=”localhost”; $user=”root”; $password=””; $con=mysql_connect($host,$user,$password); if(!$con) { echo ‘
Connected to MySQL
‘; } else { echo ‘
MySQL Server is not connected
‘; }
BUT when i run the second code replacing the name of my database and query i have error:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.28
How can it be solve? I’m new and i need to understnd it
No people, y’all need to be using PHP’s PDO connector.
mysql and mysqli connectors are gonna deprecate soon.
When I try that i get a blank page.
Hi,
I go this error on connecting to a database.
Fatal error: Uncaught Error: Call to undefined function mysql_select_db() in C:\xampp\htdocs\download\upload.php:50 Stack trace: #0 {main} thrown in C:\xampp\htdocs\download\upload.php on line 50
Below is the entire code.Please show me what is wrong:
#wrapper {
margin: 0 auto;
float: none;
width:70%;
}
.header {
padding:10px 0;
border-bottom:1px solid #CCC;
}
.title {
padding: 0 5px 0 0;
float:left;
margin:0;
}
.container form input {
height: 30px;
}
body
{
font-size:12;
font-weight:bold;
}
Upload File
if(!empty($_POST))
{
$con = mysql_connect("localhost","root","");
if (!$con)
echo('Could not connect: ' . mysql_error());
else
{
if (file_exists("download/" . $_FILES["file"]["name"]))
{
echo 'alert(” Sorry!! Filename Already Exists…”)’;
}
else
{
move_uploaded_file($_FILES[“file”][“tmp_name”],
“download/” . $_FILES[“file”][“name”]) ;
mysql_select_db(“test2”, $con);
$sql = “INSERT INTO presentation(subject,topic,file) VALUES (‘” . $_POST[“sub”] .”‘,'” . $_POST[“pre”] . “‘,'” .
$_FILES[“file”][“name”] .”‘);”;
if (!mysql_query($sql,$con))
echo(‘Error : ‘ . mysql_error());
else
echo ‘alert(“Thank You!! File Uploded”)’;
}
}
mysql_close($con);
}
?>
UPLOAD FILE PAGE
Subject:
Presentation:
File:
hello sir i have my project along with its php files with me i am confused how to link them with the database.please give me an idea about this
can you help me connect my student registration form with database using php