Jump to content

How to make a dbconnect.php file


dudejma

Recommended Posts

Hello. I was wondering how to make a file with this code:

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

mysql_select_db("virtu857_system", $con);

 

How would I say, in a file, to use this file to connect to the database, and would there be anything extra that I would need to add. Say I wanted to table data and I wanted to use this file to connect to the database, would there need to be anything extra?

Ex.

 

//code to connect to database
//would there need to be anything here that I would need to put before this:
$result = mysql_query("SELECT * FROM Users") or die("Error: " . mysql_error());
blah blah blah

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/207515-how-to-make-a-dbconnectphp-file/
Share on other sites

Your first code connects to your database, your second code selects (*=anything) from your listed table (users) the way it would work is this

 

dbconnect.php

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

mysql_select_db("virtu857_system", $con);
?>

 

index.php

<?
include 'dbconnect.php';
$query = mysql_query("SELECT * FROM Users") or die("Error: " . mysql_error());
$result=mysql_fetch_array($query);
print "{$result['field']} < I displayed that field";
blah blah blah
?>

 

Notice i just included the page into my index.php

correct me if I'm wrong, but I think it's good practice to make sure the dbconnect file isn't in your public html directory. usually 1 directory up, so you would then include it with:

 

<?php
include ('../dbconnect.php');
?>

 

This would be going back a folder. Usually you'd have dbconnect.php inside an includes folder.. or whatever preferred. The method would be..

<?php include("FOLDER_NAME/dbconnect.php"); ?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.