I have learned PDO recently so I thought of trying it out with PDO. I have 4 PHP files.
config.php files stores all the database related information.
<?php $host = "localhost"; $username = "root"; $password = "pass"; $dbname = "tbl"; ?>
init.php includes and config.php file and initializes the database connection.
<?php
include_once 'config.php';
$db = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
And there's a separate file called functions.php which has all the functions. It includes the init.php file.
<?php
include_once 'init.php';
function AddUser($_username, $_password)
{
global $db;
$db->beginTransaction();
$param1 = $_username;
$param2 = $_password;
$query = $db->prepare("INSERT INTO users(username, password) VALUES(:username, :password)");
$query->bindParam(':username', $param1, PDO::PARAM_STR);
$query->bindParam(':password', $param2, PDO::PARAM_STR);
$query->execute();
$db->commit();
}
?>
And the index.php file which displays a small form.
<?php
include_once 'functions.php';
if(isset($_POST['save']))
{
try
{
$user = $_POST['uname'];
$pass = $_POST['pass'];
AddUser($user, $pass);
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h1>Users</h1>
<form action="" method="post">
<label for="uname">Username</label>
<input type="text" name="uname" />
<br />
<label for="pass">Password</label>
<input type="password" name="pass" />
<br />
<input type="submit" name="save" value="Save" />
</form>
</body>
</html>
This works fine. But I'm just wondering of there's a way to go about this without declaring $db as global in every other function? (If I remove that line 'undefined variable' error comes up).
Or is there a better, more efficient way to accomplish this?

New Topic/Question
Reply



MultiQuote





|