How to connect to a database ?

Asked By 0 points N/A Posted on -
qa-featured

I have written a login page in PHP but how to connect to a database as I am not able to make my user to login to my page.

How can it be done?

SHARE
Best Answer by Sharath Reddy
Answered By 0 points N/A #118250

How to connect to a database ?

qa-featured

Hi  alfred

Create a connection file called connection.php.coding is given below
 
<?php
$a=mysql_connect("localhost","root","");
mysql_select_db("registration",$a);
?>
 
 
include this file in every php file of your project 
like in index.php
<?php
@session_start();
include("connection.php");
………other code lines 
?>
 
 
If you need further help feel free to ask me any time.
Answered By 0 points N/A #118251

How to connect to a database ?

qa-featured

Hello Alfred,

Check the following.

This must be the reason why you can’t connect to your database.

  • Your username and password is not setup to have an access to any database
  • You are trying to mix mysql_ and mysqli_ function. Please pick only one type and use it for any particular connection. 
  • Your firewall is blocking the port you are trying to access.

This is some simple guide to fix those error.

Hope this help.

Regards,

Elliottsims

Best Answer
Best Answer
Answered By 590495 points N/A #118252

How to connect to a database ?

qa-featured

I think there is a missing part in your login page PHP script that makes users unable to connect or login to your web page. In order for a user to connect to a database or access data from a database, you must first need to establish a connection to the database itself. Since you are using PHP, it can be done using the function “mysql_connect()”. Below is the function’s correct syntax.

  • mysql_connect(servername,username,password);

Where servername is the name of the server you want to connect to. The default is localhost:3306. Below is an example of how to create a connection to the database using PHP.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)

  die('Could not connect: ' . mysql_error());
  }

// some code
?>

The connection automatically closes when the script ends. Or, if you want to close the connection before the script terminates, you may use the function “mysql_close()”. See below for the example.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

mysql_close($con);
?>

Related Questions