I can't count results in my database with PDO - php

I have this error has shown:
Notice: Undefined variable: conn in D:\xampp\htdocs\website\core\functions\users.php on line 4
Fatal error: Call to a member function query() on null in D:\xampp\htdocs\website\core\functions\users.php on line 4
this is connect database
connect.php
<?php
$servername = "localhost";
$user = "root";
$passwd = "";
$dbname = "userdata";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $passwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
die($exc->getMessage());
}
?>
and in this part I have the problem
users.php
<?php
function user_exists($username){
$sql ="SELECT COUNT('id') FROM users where username = '$username'";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(count($result)){
$res = 0;
}else {
$res = 1;
}
return $res;
}
?>
and this where I connected users.php with connect.php
init.php
<?php
session_start();
require 'database/connect.php';
require 'functions/users.php';
require 'functions/general.php';
$errors = array();
?>

This is a variable scope problem.
Because $conn is set / declared outside of your function, you do not have access to it inside of your function.
Modify your function as follows:
function user_exists($username){
// This gets you access to the $conn variable inside the function.
global $conn;
$sql ="SELECT COUNT('id') FROM users where username = '$username'";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(count($result)){
$res = 0;
}else {
$res = 1;
}
return $res;
}

Related

Cant connect mysql and php

I tried to connect my MySQL database kuvarskir with my PHP code. Then inputted this into html:
<?php
include "mysql.php";
$recepti = execute_sql("SELECT * FROM recepti");
foreach($recepti as $recept)
{
?>
<article>
<h2><?=$recept["naziv"]?></h2>
<i><?=$recept["sastojci"]?></i>
<p><?=$recept["uputstvo"]?></p>
</article>
<?php
}
?>
but its not working.
i think there is error with mysql.php file, here's the code:
<?php
function init_sql()
{
global $conn;
$host = "localhost";
$db = "kuvarskir";
$username = "root";
$password = "root";
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password, $pdo_options);
}
catch(PDOException $e)
{
die("Database connection failed!");
}
}
function execute_sql($sql, $params=[])
{
global $conn;
if ($conn == null)
init_sql();
try
{
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$data = array();
if ($stmt->columnCount() == 0) //INSERT / UPDATE
return $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
$data[] = $row;
return $data;
}
catch(Exception $e)
{
die("somting glitched. error is: $e");
}
}
?>
maybe, there is problem with my localhost, which is localhost:8080/phpmyadmin
also here is picture of database

Connection is not defined

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);
}

Issue with PDO Connection

i am new to this so dont be rude :D
I have 3 file: database.php, init.php and user.php
Here the init.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require 'database.php';
require 'functions/user.php';
$errors = array();
Here the database.php:
<?php
$db_host = "localhost";
$db_name = "xxxx";
$db_user = "xxxx";
$db_pw = "xxxx";
try {
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pw);
} catch(PDOException $e) {
die("Verbindung fehlgeschlagen: " . $e->getMessage());
}
And here the user.php:
<?php
function userExists($user) {
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
So the error message:
Notice: Undefined variable: conn in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 Fatal error: Call to a member function prepare() on null in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4
The function userExists() is called in another file named login.php. In login.php i have already required init.php. The error message appears when i want to login.
So i hope you can help me.
Thx
$conn is not available in your function since it is in a different scope. Pass it as a parameter or declare it as a global variable.
function userExists($user, $conn){
// ...
}
or
function userExists($user){
global $conn;
// ...
}
In your userExists function you are calling $conn variable which isn't global scope (Give a small look here)..
You can use one of these:
function userExists($user, $conn){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
function userExists($user){
global $conn; //<--- bad practi
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
use of $GLOBALS variable
function userExists($user){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}

how to use a variable outside a function

i have this initialization file called init.php which I have declared a variable called $db for a mysqli connection. Below is my code.
<?php
ob_start();
session_start();
define('DBHOST', '127.0.0.1');
define('DBUSER', 'root');
define('DBPASSWORD', '');
define('DBNAME', 'mydb');
$db = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);
if ($db->connect_error) {
header('Location: 404.php');
}
require_once 'functions/User.php';
require_once 'functions/Sanitize.php';
As you can see I required User.php inside the function folder, and on the User.php file i have this code
<?php
function login($idnumber, $username, $password) {
$idnumber = sanitize($idnumber);
$username = sanitize($username);
$password = sanitize($password);
$hashed_password = get_hashed_password($username);
}
function get_hashed_password($username) {
$username = sanitize($username);
$sql = "SELECT `password` FROM `users` WHERE `username` = ?";
$stmt = $db->prepare($sql);
if(!$stmt) {
echo 'invalid sql statement';
}
die();
}
On the get_hashed_password() function i used the variable $db but i got an error message saying
Notice: Undefined variable: db in D:\xampp\htdocs\sample\functions\User.php on line 15
Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\sample\functions\User.php on line 15
Can someone help me how can I used the variable $db in any of my functions? Thanks in advance!
Call $db as global
function get_hashed_password($username) {
global $db;
//...
}
you can use $GLOBALS inside the function like this
$your_var = "something";
function abc()
{
$your_var = $GLOBALS['your_var'];
}
UPDATE 2 :
function get_hashed_password($username) {
$username = sanitize($username);
$sql = "SELECT `password` FROM `users` WHERE `username` = ?";
$db = $GLOBALS['db'];
$stmt = $db->prepare($sql);
if(!$stmt) {
echo 'invalid sql statement';
}
die();
}

"Undefined Variable" notice

Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.

Categories