php fluentpdo -> Undefined variable: fpdo - php

I am confused with the include stuff i think, I don't know where exactly its wrong.
The Connection file with fluentpdo
<?php
error_reporting(E_ALL | E_STRICT);
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/libs/FluentPDO/FluentPDO.php');
$pdo = new PDO("mysql:dbname=ummah", "pluto","admin");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$fpdo = new FluentPDO($pdo);
//~ $software->debug = true;
?>
if i am using to insert data like this as below:
Insert.php
<?php
include '../connect.inc.php';
function inReg(){
try{
$values = array('name' 'xyz', 'pwd' => '1234');
$query = $fpdo->insertInto('users')->values($values)->execute();
echo 'success';
return;
}catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
?>
Not a problem with above stuff, its just in a php file. What I am trying to do is use a class as i did below:
Connection file is same.
DBInsert.php
<?php
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/bin/connect.inc.php');
class DBInsert {
function Insert($table, $values){
try{
$query = $fpdo->insertInto($table)->values($values)->execute();
return 'success';
}catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
}
?>
now i am creating object of above class and trying to call the Insert function like this:
Test.php
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/bin/dao/DBInsert.php');
function Signup(){
$values = array('name' => 'xyz', 'pwd' => '1234');
$db = new DBInsert();
echo $db->Insert('users',$values);
}
Signup();
?>
So when i am accessing Test.php i am getting the following error:
Notice: Undefined variable: fpdo in E:\Program Files\Apache Software
Foundation\Apache2.2\htdocs\Mark20\bin\dao\DBInsert.php on line 15
Fatal error: Call to a member function insertInto() on a non-object in
E:\Program Files\Apache Software
Foundation\Apache2.2\htdocs\Mark20\bin\dao\DBInsert.php on line 15
I am new to php, not totally new also :). So a little help is greatly appreciated.
Thanks and Regards
Adeeb

Global variables are not in scope in functions by default. You need to do:
function inReg(){
global $fpdo;
try{
$values = array('name' 'xyz', 'pwd' => '1234');
$query = $fpdo->insertInto('users')->values($values)->execute();
echo 'success';
return;
}catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
or pass $fpdo as a parameter to the function.

Related

Why doesn't the Insert work for me in SQLITE3?

when executing the form, the data is not inserting. I have activated SQLITE3 and I am not skipping any type of error.
The echo of the try is to see what was wrong but nothing. I see everything right.
Does anyone help me?
$username = $_POST['nombre'];
$clave = $_POST['clave'];
$apenom = $_POST['apenom'];
try {
$bd = new SQLite3("test");
//preparamos la sentencia
echo "INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')";
$bd->exec("INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')");
/* while ($row = $resultado->fetchArray()) {
echo "{$row['username']} {$row['clave']} {$row['apenom']} \n";
} */
} catch (\Throwable $th) {
echo $th;
}
Do take the advice from the comments into account, database security is not something you should 'wing'...
As for a little help on setting up a connection and importantly debugging if anything goes wrong so you know what to fix, the following 'skeleton' might help:
<?php
try {
// connect to your database
$sqlite = new SQLite3('test.db');
}
catch (Exception $e) {
// if no connection could be established a exception is thrown
echo $e->getMessage();
}
// your query
$query = '...';
$result = $sqlite->query($query); // result object (FALSE on error)
if (!$result) {
// query failed for some reason...
echo $sqlite->lastErrorMsg();
} else {
// do something with result
}

Checking if email address exists in SQL database with php

I am doing a school assignment which has to contain a page for users to register. I am getting an error with checking if their email address is already in the database, but I can't figure out why. The error is:
Notice: Undefined variable: kapcsolat in /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php on line 39
Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/hallgatok/jyhv6c/www/wf2/php_bead/database.php:9 Stack trace: #0 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(9): lekerdezes(NULL, 'SELECT * FROM `...', Array) #1 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(39): letezik(NULL, 'koostamas199753...') #2 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(53): validate(Array, Array, Array) #3 {main} thrown in /home/hallgatok/jyhv6c/www/wf2/php_bead/database.php on line 9
My database.php, where I connect:
database.php
<?php
function kapcsolodas($kapcsolati_szoveg, $felhasznalonev = '', $jelszo = '') {
$pdo = new PDO($kapcsolati_szoveg, $felhasznalonev, $jelszo);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function lekerdezes($kapcsolat, $sql, $parameterek = []) {
$stmt = $kapcsolat->prepare($sql);
$stmt->execute($parameterek);
return $stmt->fetchAll();
}
function vegrehajtas($kapcsolat, $sql, $parameterek = []) {
return $kapcsolat
->prepare($sql)
->execute($parameterek);
}
$kapcsolat = kapcsolodas(
'mysql:host=localhost;dbname=****;charset=utf8',
'****', '****');
?>
And the page which does the work:
register.php
<?php
include('database.php');
///////////////////////////////////
function letezik($kapcsolat, $felhasznalonev) {
$felhasznalok = lekerdezes($kapcsolat,
"SELECT * FROM `felhasznalok` WHERE `felhasznalonev` = :felhasznalonev",
[ ":felhasznalonev" => $felhasznalonev ]
);
return count($felhasznalok) === 1;
}
function regisztral($kapcsolat, $teljes_nev, $felhasznalonev, $jelszo) {
$db = vegrehajtas($kapcsolat,
"INSERT INTO `felhasznalok` (`teljes_nev`, `felhasznalonev`, `jelszo`)
values (:teljes_nev, :felhasznalonev, :jelszo)",
[
":teljes_nev" => $teljes_nev,
":felhasznalonev" => $felhasznalonev,
":jelszo" => password_hash($jelszo, PASSWORD_DEFAULT),
]
);
return $db === 1;
}
function validate($post, &$data, &$hibak) {
if (trim($post['nev']) === '') {
$hibak[] = 'Teljes név kötelező!';
}
else {
$data['nev'] = $post['nev'];
}
if (trim($post['email']) === '') {
$hibak[] = 'E-mail cím kötelező!';
} else if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
$hibak[] = "Hibás e-mail cím!";
} else if (letezik($kapcsolat, $post['email'])) { <========This is line 39, but $kapcsolat was defined in database.php
$hibak[] = "Ehhez az e-mail címhez már tartozik felhasználói fiók!";
}
else {
$data['email'] = $post['email'];
}
$data['jelszo'] = $post['jelszo'];
return count($hibak) === 0;
}
$hibak = [];
if ($_POST) {
if (validate($_POST, $data, $hibak)) {
regisztral($kapcsolat, $data['nev'], $data['email'], $data['jelszo']);
header("Location: index.php");
exit();
}
}
?>
The error only occurs when that part of the if statement runs. I just can't figure out what the problem is.What am I doing wrong?
As I said in a comment, your variable $kapcsolat is defined in your file database.php, but is used in the function validate.
When you create a function, all variables used in it are supposed to be local variables.
I suggest to take this variable as parameter instead of using the global variable, it's more flexible. But if you really want to use this variable, you have to declare $kapcsolat as global.
In register.php you should use:
<?php
function validate($post, &$data, &$hibak) {
global $kapcsolat; //IMPORTANT IS HERE
//...Some code
}
See the global keyword

I have an issue with my php code, I need to divide function for my database

I tried to divide the function to create a table and to connect to the database but the php function that creates the table does not work to me, does anyone know how to fix this problem? I enclose the php code and the index.
prova.php:
class db_mysqls
{
public function connect()
{
$username="username";
$password="password";
try
{
$connection = new PDO("mysql:host=localhost;dbname=ijdb",$username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo ' <br> Connection Complete';
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
public function createDB()
{
try
{
$sql="CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL)";
// use exec() because no results are returned
$connection->exec($sql);
echo "Table MyGuests created successfully";
}
catch (PDOException $e)
{
echo 'Creation failed: ' . $e->getMessage();
}
}
}
?>
index.php:
<html>
<head>
<title>Index.html</title>
</head>
<body>
Eseguo prova.php <br>
<?php
include 'prova.php';
$db = new db_mysqls();
echo 'New Database Object Created';
$db->connect();
$db->createDB();
?>
</body>
</html>
The problem is variable scope. All your variables are local. You need to make a private class member to store the connection object so the same connection can be accessed by both methods.
<?php
class db_mysqls
{
private $connection;
public function connect()
{
$username="username";
$password="password";
try
{
$this->connection = new PDO("mysql:host=localhost;dbname=ijdb",$username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo ' <br> Connection Complete';
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
public function createDB()
{
try
{
$sql="CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL)";
// use exec() because no results are returned
$this->connection->exec($sql);
echo "Table MyGuests created successfully";
}
catch (PDOException $e)
{
echo 'Creation failed: ' . $e->getMessage();
}
}
}
?>

why is my class not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Guys i'm scratching my head for this problem. As, i get this error from my openshift log
PHP Fatal error: Call to a member function totalids() on a
non-object in
/var/lib/openshift/573dc0da2d5271d357000294/app-root/runtime/repo/st&com.php
on line 46, referer: http://express-pad4u.rhcloud.com/
And doing var_dump on $conn and $project from dbconfig.inc.php file in st&com.php gives the following message:
object(PDO)#1 (0) { } object(projecteg)#2 (4) {
["_db":"projecteg":private]=> object(PDO)#1 (0) { } ["query"]=> NULL
["stmth"]=> NULL ["conn"]=> NULL }
here is my dbconfig.inc.php code:
session_start();
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST') . ':' . getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER', getenv('**********'));
define('DB_PASS', getenv('**********'));
define('DB_BASE', 'project');
define('DB_PORT', getenv('OPENSHIFT_MYSQL_DB_PORT'));
try {
$conn = new PDO("mysql:host=" . getenv('OPENSHIFT_MYSQL_DB_HOST') . ";dbname=" . DB_BASE . "", "********", "*********");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exc) {
echo $exc->getMessage();
}
include 'classes.inc.php';
$project = new projecteg($conn);
here is the code for st&com.php file:
<?php
//error_reporting(0);
include_once "includes/dbconfig.inc.php";
$status_replies="";
$status_list="";
$statusui_edit="";
$isowner="";
$is_friend="";
$statusdeletebutton='';
$reply_delete_button="";
$load= (int)($_POST['load'])*2;
var_dump($conn);
echo '<br>';
var_dump($project);
echo '<br>';
function hashtags($dat) {
$regex="/#+([a-zA-z0-9._-]+)/";
$dat1= preg_replace($regex, '$0', $dat);
return $dat1;
}
function taggingsys($dat) {
$regex="/#+([a-zA-z0-9!._-]+)/";
$dat1= preg_replace($regex, '$0', $dat);
return $dat1;
}
function ff(&$s) {
//$conn="";
//require_once 'includes/dbconfig.inc.php';
$output=array();
// $friends=array();
//$project= new \projecteg($conn);
// $totalids=array();
$verify_friend=array();
foreach ($s as $i=> $r ){
//array_push($friends, $r);
$r["friend_one"] == $_SESSION['uname'] ? $friends[]= $r["friend_two"] : $friends[] = $r["friend_one"];
echo '<pre>';var_dump($friends);echo '</pre>';
$verify_friend= $project->totalids($friends[$i]);
/* foreach ($friends as $v) {
echo '<br><h1>'; print_r($v); echo '</h1></br>';
echo '<br>';
// var_dump($verify_friend);
// array_push($totalids, $verify_friend);
}
echo '<pre>'; var_dump($verify_friend); echo '</pre>'; */
array_push($output, $verify_friend);
}
return $output;
}
$f = array();
$stmt= $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and accepted='1'");
$stmt->bindparam(":session",$_SESSION['uname']);
$stmt->execute();
$f=$stmt->fetchAll();
$ids= ff($f);
foreach ($ids as $i=>$v){
$id=$v[$i]['user_id'];
//fetch user_id from update table in db and inject it to the feed query.
$totalUpdates=$project->totalUpdates1($id,$load);
$total_sess_count=$project->totalupdatescount($id);
foreach ($totalUpdates as $j=>$row1) {
$updateid=$row1['update_id'];
$account_name=$row1['account_name'];
$u_id=$row1['user_id_u'];
$author=$row1['author'];
$post_date=$row1['time'];
$title= stripslashes($row1['title']);
$data= stripslashes($row1['update_body']);
$data1= hashtags($data);
//$data1= taggingsys($data0);
$pic=$project->viewByUname($author);
$uid=$pic['user_id'];
$datemade = strftime("%B %d", strtotime($post_date));
$avatar=$pic['avatar'];
if ($avatar!=""){
$feed_pic='user/'.$uid.'/'.$avatar;
} else {
$feed_pic='img/avatardefault.png';
}
//other lengthy logic
here is the class logic:
<?php
class projecteg
{
private $_db;
public $query;
public $stmth;
public $conn;
public function __construct($conn)
{
$this->_db = $conn;
}
public function totalids($friend)
{
try {
$sql2 = "select user_id from user where uname=:session or uname=:friend and activated='1'";
$stmth = $this->_db->prepare("$sql2");//Check here syntax of $db
$stmth->bindValue(":session", $_SESSION['uname']);
$stmth->bindValue(":friend", $friend);
$stmth->execute();
return $stmth->fetchAll();
} catch(PDOException $exc) {
echo $exc->getMessage();
}
}
}
how do i make my method and conn to work.
You are trying to use $project inside a function ff() without passing it in or declaring it inside the function so it doesn't exist inside the scope of that function. Do some research on scope that should help you out. But for now you need to pass in $project to ff() if you want to use it. Something like this:
function ff(&$s,$project) {
...
}
$ids = ff($f,$project);
That is assuming you want to use the $project you have already declared. If not you will need to create a new instance inside the function like Patrick-Q said in the comments.

Crate/PDO Usage Examples

Has anyone successfully installed Crate/PDO.
I seem to be banging my head against this one.
I have used composer to create the json file and when i try to
<?php
require 'vendor/autoload.php';
try {
$dbh = new PDO('crate:localhost:4200');
foreach($dbh->query('SELECT * from testtable') as $row) {
print_r($row);
}
$dbh = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
It comes up with error Could not find driver.
Any help or installation documents would be great. anyone got any example code working.
The Crate PDO adapter is not official supported and included by PHP PDO, so the Crate PDO class must be used instead of the standard PDO class.
You should either import the Crate\PDO\PDO class by use Crate\PDO\PDO;
or use a full qualified classname:
<?php
require 'vendor/autoload.php';
try {
$dbh = new \Crate\PDO\PDO('crate:localhost:4200', null, null, []);
foreach($dbh->query('SELECT * from testtable') as $row) {
print_r($row);
}
$dbh = null;
}
Just do it this way and you will be okay. Give me a shout if you needs more help.... Sectona
pdo_connect.php
<?php
$db = new PDO (
'mysql:host=localhost;dbname=sectona_db;charset=utf8',
'root', // username
'root6a' // password
);
?>
<?php
require("pdo_connect.php");
$result = $db->prepare('SELECT table_data,table_name FROM testable');
$result->execute(array(
'
));
while ($row = $result->fetch()) {
$tb1=htmlentities($row['table_data'], ENT_QUOTES, "UTF-8");
$tb2=$pid=htmlentities($row['table_name'], ENT_QUOTES, "UTF-8");
echo $tb1;
echo $tb2;
}
?>

Categories