I have two files, a functions.php which contains a PDO object to connect to a database and contains columns as variables and a index.php to output the variable containing the data. the database connection works however when I try to echo a variable from my function it is returned undefined, What am i doing wrong;
functions.php
<? php
function connectDB() {
$hostname = 'xxxxxxxx';
$db = 'xxxxxxx';
$user = 'xxxxxxxx';
$pass = 'xxxxxxx';
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "//my query";
$query = $dbh->prepare($sql);
$query->execute(array('//value','//value'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$var1 = $r['column1'];
$var2 = $r['column2'];
$var3 = $r['column3'];
$var4 = $r['column4'];
$var5 = $r['column5'];
endwhile;
}
?>
index.php
<?php
include 'functions.php';
?>
<?php
try {
connectDB();
echo 'You are connected to Database';
echo $var1;
$dbh = null;
}
catch(PDOException $e) {
echo $e -> getMessage();
}
?>
those variables are by default local to your connectDB() function, so you will have to either declare them in global scope beforehand, or use the $GLOBALS to set them:
Method 1
<? php
$var1 = '';
$var2 = '';
$var3 = '';
$var4 = '';
$var5 = '';
function connectDB() {
$hostname = 'xxxxxxxx';
$db = 'xxxxxxx';
$user = 'xxxxxxxx';
$pass = 'xxxxxxx';
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "//my query";
$query = $dbh->prepare($sql);
$query->execute(array('//value','//value'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$var1 = $r['column1'];
$var2 = $r['column2'];
$var3 = $r['column3'];
$var4 = $r['column4'];
$var5 = $r['column5'];
endwhile;
}
?>
Method 2
<? php
function connectDB() {
$hostname = 'xxxxxxxx';
$db = 'xxxxxxx';
$user = 'xxxxxxxx';
$pass = 'xxxxxxx';
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "//my query";
$query = $dbh->prepare($sql);
$query->execute(array('//value','//value'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$GLOBALS['var1'] = $r['column1'];
$GLOBALS['var2'] = $r['column2'];
$GLOBALS['var3'] = $r['column3'];
$GLOBALS['var4'] = $r['column4'];
$GLOBALS['var5'] = $r['column5'];
endwhile;
}
?>
Sincerely, your copy-paste-service :)
you can generally access variables in one of two ways, either as a parameter passed to the function or by declaring, within the function, the variable as global. Hope the following helps a little
function banana( $externalvar=false ){
echo $externalvar;
}
or
function banana(){
global $externalvar;
echo $externalvar;
}
The smart code should use yield keyword:
function connectDB() {
// ...
$output = [];
$index = 0;
while ($r = $query->fetch()):
yield $r;
endwhile;
}
Then:
foreach ($connectDB() as $row)
echo $row['column1'], PHP_EOL;
echo $row['column2'], PHP_EOL;
echo $row['column3'], PHP_EOL;
endforeach;
Otherwise, just return an array, then extract:
function connectDB() {
// ...
$output = [];
$index = 0;
while ($r = $query->fetch()):
++$index;
foreach($r as $key => $value) {
$output[$name . '_' . $index] = $value;
}
endwhile;
return $output;
}
Then:
$vars = connectDB();
extract($vars);
;
echo $column1_1, PHP_EOL;
echo $column2_1, PHP_EOL;
echo $column3_1, PHP_EOL;
;
echo $column1_2, PHP_EOL;
echo $column2_2, PHP_EOL;
echo $column3_2, PHP_EOL;
The second purpose is very ugly.
Related
I have the following code
<?php
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function getIPforBDD(){
return $_SERVER['REMOTE_ADDR'];
}
function UpdateUserProfile()
{
$requete = "SELECT * FROM users WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
if($resultat->rowCount() == 0)
exit();
foreach($result as $ligne)
{
$userIP = $ligne['ip'];
$userhasFinish = $ligne['finish'];
$userLastPage = $ligne['lastPage'];
}
}
function CheckUserPosition()
{
UpdateUserProfile();
if(!$userExist)
AddUser();
return GetUserStatus();
}
function GetUserStatus()
{
$page;
if($userHasFinish)
$page = "end.php";
else
$page = $userLastPage;
return $page;
}
function AddUser()
{
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
function SavePageInBDD($page){
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
?>
But, I have a problem when I use it
( ! ) Notice: Undefined variable: dbh in C:\wamp64\www\HawkI\bdd.php
on line 66
I do not understand correctly how PHP work it's the first time I use it, but I tried to make
global $dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
That doesn't work too.
Also, it seems that value that are put outside of functions are not global like it would be in js, how can I make something accessible from everywhere (like file that include that file)
Thanks
Better way would be to do something like this:
function getDB(){
$dbh = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
And than in your functions do this:
function AddUser()
{
$dbh = getDB();
if(!is_null($dbh)){
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
}
To use $dbh inside a function, you need to include global keyword inside the function scope.
You can find the global keyword explanation here http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global
function AddUser()
{
global $dbh;
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
You may use like this
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
$dbh = NULL;
function db () {
try {
if ($GLOBALS['dbh']===NULL){
$GLOBALS['dbh'] = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
}
return $GLOBALS['dbh'];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function SavePageInBDD($page){
$dbh = db();
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
I have 2 functions each containing a PDO object in a functions.php file that output html and are called in a different file. I am trying to organise my code and have put my database information outside of those functions and using them as globals.
I have read that using globals are bad practice so I though of having a class with the two functions inside, but as there is html inbetween the functions i'm finding it difficult to place them inside the class properly if it's even possible. best way I can demonstrate is with my code. How can I organise this in a class?
<?php
$hostname = 'host';
$db = 'database';
$user = 'username';
$pass = 'password';
?>
<?php function connectDB () {
global $hostname, $db, $user, $pass;
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "query 1";
$query = $dbh->prepare($sql);
$query->execute(array(//'placeholder',//'placeholder'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$variable1 = $r['column1'];
$variable2 = $r['column2'];
$variable3 = $r['column3'];
$variable4 = $r['column4'];
$variable5 = $r['column5'];
$variable6 = $r['column6'];
$variable7 = $r['column7'];
?>
//html code
<?php endwhile; } ?>
<?php function connectDB2 () {
global $hostname, $db, $user, $pass;
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "query 2";
$query = $dbh->prepare($sql);
$query->execute(array(//'placeholder',//'placeholder'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$variable1 = $r['column1'];
$variable2 = $r['column2'];
$variable3 = $r['column3'];
$variable4 = $r['column4'];
$variable5 = $r['column5'];
$variable6 = $r['column6'];
$variable7 = $r['column7'];
?>
//html code
<?php endwhile; } ?>
only work when $i=0;
<?php
include 'db.php';
$con = new db();
$db = $con->getConnection();
$i = 0;
while($i <= 10){
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
?>
the following code work fine but its take too much time and for that I want to reuse connection
<?php
include 'db.php';
$i = 0;
while($i <= 10){
$con = new db();
$db = $con->getConnection();
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
?>
and db class
<?php
class db {
var $_host = "localhost";
var $_user = "root";
var $_password = "";
var $_database = "test";
var $db;
public function __construct() {
$this->db = new mysqli($this->_host, $this->_user, $this->_password, $this->_database);
$this->db->set_charset("utf8");
}
public function getConnection() {
if ($this->db->connect_errno > 0) {
die('Unable to connect to database [' . $this->db->connect_error . ']');
}
return $this->db;
}
}
How I can execute query in a single connection
you should instantiate the db object outside of the loop, and close it after:
$con = new db();
$i = 0;
while($i <= 10){
$db = $con->getConnection();
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
Try moving the db connection and close functions outside the while loop. You can execute multiple queries on same connection.
include 'db.php';
$con = new db();
$db = $con->getConnection();
$date = date('Y-m-d');
$i = 0;
while($i <= 10){
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
When I run this php file shows me the error SQLSTATE [HY000]: General error. Why?
function Gethotspots($db) {
$regId = $_GET['regId'];
$sql = $db->prepare("INSERT INTO notificaciones (regId) VALUES ('" . $regId . "')");
$sql->execute();
$i = 0;
$pois = $sql->fetchAll(PDO::FETCH_ASSOC);
if (empty($pois)) {
$response["productos"] = array();
}
else {
foreach ($pois as $poi) {
$poi["actions"] = array();
$response["productos"][$i] = $poi;
$i++;
}
}
return $response["productos"];
}
$dbhost = "localhost";
$dbdata = "anuncios";
$dbuser = "root";
$dbpass = "";
try {
$db = new PDO("mysql:host=$dbhost; dbname=$dbdata", $dbuser, $dbpass, array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$response = array();
$response["productos"] = Gethotspots($db);
if (empty($response["productos"])) {
$response["errorCode"] = 20;
$response["errorString"] = "Ningun producto encontrado.";
} // if
else {
$response["errorCode"] = 0;
$response["errorString"] = "Todo correcto";
}
$jsonresponse = json_encode($response);
header('Access-Control-Allow-Origin: *');
echo $jsonresponse;
$db = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
Thanks all!
I'm trying to retrieve data from my table using PDO, only I can't seem to output anything to my browser, I just get a plain white page.
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$lastIndex = 2;
$sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20"
$sth = $conn->prepare($sql);
$sth->execute(array(':lastIndex' => $lastIndex));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo 'ALL STYLING ETC RESULTS HERE';
$c++;
}
$conn = null; // Disconnect
}
EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}