Using a function in php to create a database connection? - php

So really I just want to make stuff easier to read and just create a function where I can call upon the database connection, the below is what i've tried to do to do far.
So far, it doesn't work, it doesn't bring any message at all so presumably it isn't going into the try.
functions.php
function getDBConnection()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
}
catch(PDOException $e)
{
echo 'An error occured talking to the DB';
}
return $db;
}
and then do
submittest.php
require('functions.php');
getDBConnection(); //return $db
$username = 'donkey';
$password = 'donkey';
$email = 'donkey';
$county = 'donkey';
try
{
//Prepare and execute an insert into DB
$st = $db->prepare("INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:county)");
$st->execute(array(':username' => $username, ':password' => $password, ':email' => $email, ':county' => $county));
echo 'Success';
}
catch (PDOException $e)
{
echo 'An error occurred talking to the DB';
}
?>

$db = getDBConnection(); //return $db

Related

why php-pdo don't insert values [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm setting to do a simple query using PDO. However, when I run it, it does not insert. The database is called "famous" and the table is called "pessoas" containing only two columns called (codigo and nome).The connection works, but when I execute it return "Error to save".
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;bdname=pessoas';
$user = 'root';
$password = 'init4289';
try{
$pdo = new PDO($dsn, $user, $password);
echo 'SUCESSO AO CONECTAR!';
return $pdo;
}catch(PDOExeption $ex){
echo 'erro: '. $ex->getMessage();
}
}
?>
#end page "conexao_pdo.php"
<?php
include 'conexao_pdo.php';
$conn = getConnection();
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if($stmt->execute()){
echo 'Success to save';
}else{
echo '<p>'.'Error to save';
}
?>
You may consider the following:
probably it's just a typing error - bdname should be dbname in 'mysql:host=localhost;bdname=pessoas'
database and table names - 'famous' and 'pessoas' in the question, 'pessoas' and 'famous' in the code
include exception handling with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
your function getConnection() should return false on failure
Code, based on your question:
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;dbname=pessoas';
$user = 'root';
$password = 'init4289';
try {
$pdo = new PDO(
$dsn,
$user,
$password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
echo 'SUCESSO AO CONECTAR!';
} catch (PDOExeption $ex){
echo 'Error: '. $ex->getMessage();
return false;
}
return $pdo;
}
?>
<?php
include 'conexao_pdo.php';
// Connection
$conn = getConnection();
if ($conn === false) {
exit;
}
// Statement
try
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if ($stmt->execute()) {
echo 'Success to save';
} else {
echo '<p>'.'Error to save';
}
} catch (PDOExeption $ex){
die ('Error: '. $ex->getMessage());
}
?>

How to use PDO prepare more than oncee in a class

class dbConnection {
function connect(){
try{
$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
}
class student{
public $link;
public function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
public function checkLogin($username,$password){
$query = $this->link->prepare("SELECT * FROM studentprofiles where UserName = :uname AND LogPassword = (select md5(:upassword));");
$query->execute(array(':uname' => $username, ':upassword' => $password));
$count = $query->rowCount();
if($count === 1){
$this->setSession($username);
}
return $count;
$query = null;
}
public static function display(){
$query = $this->link->prepare("SELECT ForeName, Surname FROM studentprofiles where UserName = :uname;"); //getting error here: Fatal error: Using $this when not in object context
$query->execute(array(':uname' => self::getSession()));
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
printf (" <span id='WelcomeName'> Welcome: %s %s\n </span>",$row[0],$row[1]);
}
$query = null;
}
}
Error using $this again to prepare another select statement, how do I use it again for another function in the same class? Thank You
Appreciate any help, really stuck on this problem
hi you can check you code and i prefer asign in to value the conection example
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and in your function you make some one how this
function connect(){
try{
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
in a complete example this:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
please try and good luck

PHP PDO Common Error i Faced

I gotten this error
Database Connected successfully Fatal error: Call to a member function prepare() on a non-object in D:\home\site\wwwroot\DatabaseMethods.php on line 22
I can't seem to find what is causing this any one could point out whats wrong please enlighten me.
I have tried to call the connection before running the prepared statement but cant seems to work or what should i do
Thanks in advance
DatabaseMethods.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("DatabaseConnection.php");
date_default_timezone_set("Asia/Singapore");
//Register
function RegisterUser($email , $password)
{
$conn = connect_db();
$stmt = null;
$stmt = $conn->prepare("INSERT INTO secure_login (email,password,created_dt) VALUES(?,?,?)"); //ERROR LINE
$stmt->execute(array($email, $password , date("Y-m-d h:i:s")));
if( $stmt )
{
return "success";
}
else
{
return "Failed";
}
}
//date("Y-m-d h:i:s")
//End Register
?>
DatabaseConnection.php
<?php
function connect_db()
{
$servername = "xxxx";
$username = "xxx";
$password = "xxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=xxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
Answer
<?php
function connect_db()
{
$servername = "xxx";
$username = "xxx";
$password = "xxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=xxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database Connected successfully";
return $conn;
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>

Fetching PDO - $handler vs $stmt?

I am VERY new to PHP / PDO, so please be gentle...
I am trying to enter code into my database and then fetch it into a webpage. I am able to do the first but am having difficulty displaying it. I am wondering if it's because i'm trying to combine $stmt and $handler together?
This is my code for entering the information into the database:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO survey (storename, receipt, date_visit)
VALUES (:storename, :receipt, :date_visit)");
$stmt->bindParam(':storename', $storename);
$stmt->bindParam(':receipt', $receipt);
$stmt->bindParam(':date_visit', $date_visit);
// insert a row
$storename = $_POST['storename'];
$receipt = $_POST['receipt'];
$date_visit = $_POST['date_visit'];
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
It works perfectly.
This is my code for fetching information from my database.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$handler->setAttribute(PDO::ATRR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class SurveyEntry {
public $id, $storename, $receipt, $date_visited,
$entry;
public function __construct() {
$this->entry = "{$this->storename} posted: {$this->receipt}";
}
}
$query = $handler->query('SELECT * FROM survey');
$query->setFetchMode(PDO::FETCH_CLASS, 'SurveyEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
I can confirm that it connects correctly, but I can't get it to display any information. I'm wondering if it's something to do with the difference in $stmt and $handler that i'm using? I've been following tutorials online and have quite possibly mixed 2 tutorials together to try and achieve what i'm looking for.
UPDATE:
I managed to get it to work by updating how I called from the database:
$host = "localhost";
$dbname = "test";
$user = "test";
$password = "test";
$handler = new PDO( "mysql:dbname=$dbname;host=$host" , $user , $password );
Figured it out - I had 'ATRR_ERRMODE' instead of 'ATTR_ERRMODE' (typo)
how are you?
You should try to fix it:
1- Two different connections:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories