Reputation: 153
I need to create a website which allows a user to create a job which is saved to a database and then all the jobs can be viewed from a different page on the website. I've managed to get this to work but I've had to duplicate all of the MySQL log in set up in PHP. I'd like to avoid this duplication and tried using an autoloader but with no success. Basically the first 5 variables are repeated from a separate page where I'm adding the data into the database and I'd like to avoid this if possible. The code itself works I just feel like there must be a way to avoid repetition here.
<?php
$server = '192.168.56.2';
$username = 'student';
$password = 'student';
$schema = 'assignment';
$pdo = new PDO('mysql:dbname=' . $schema . ';host=' . $server, $username, $password);
$file ='section3.php';
echo 'Last Edited: ' .date('d/m/Y', filemtime($file));
$results = $pdo->query('SELECT * FROM jobs');
foreach ($results as $row) {
echo '<p>' . $row['title']." " . $row['salary'] ." ". $row['location'] ." ". $row['description'].'</p>';
}
?>
Upvotes: 1
Views: 92
Reputation: 6860
Put your DB credentials into separate php-file and require_once
it from each script where needed
db.php:
$server = '192.168.56.2';
$username = 'student';
$password = 'student';
index.php:
require_once('db.php');
$schema = 'assignment';
$pdo = new PDO('mysql:dbname=' . $schema . ';host=' . $server, $username, $password);
// ...
Also RTM on difference between
Upvotes: 1
Reputation: 5246
The usual approach is to place the database connection data (and usually the code that creates the connection) into a separate file and then require_once()
that file in each page that needs to connect to the db. eg:
db_connect.php:
<?php
$server = '192.168.56.2';
$username = 'student';
$password = 'student';
$schema = 'assignment';
$pdo = new PDO('mysql:dbname=' . $schema . ';host=' . $server, $username, $password);
otherpage.php:
<?php
require_once 'db_connect.php';
$file ='section3.php';
echo 'Last Edited: ' .date('d/m/Y', filemtime($file));
$results = $pdo->query('SELECT * FROM jobs');
foreach ($results as $row) {
echo '<p>' . $row['title']." " . $row['salary'] ." ". $row['location'] ." ". $row['description'].'</p>';
}
?>
As usual, I leave error handling as an exercise for the reader.
Upvotes: 0