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
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

Link to comment
Share on other sites

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"); ?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.