Issue with PDO Connection - php

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

Related

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

Getting user and encrypted password from datebase

i got the following code:
public function getUserByNameAndPassword($name, $password) {
$stmt = $this->conn->prepare("SELECT salt FROM `users` WHERE name = ?");
$stmt->bind_param("s", $name);
if ($stmt->execute()) {
$stmt->store_result();
$salt = $stmt->get_result();
}
$encryptedpassword = $this->checkhashSSHA($salt,$password);
$stmt = $this->conn->prepare("SELECT * FROM `users` WHERE name = ? AND encrypted_password = ?");
$stmt->bind_param("ss", $name, $encryptedpassword);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
}
else {
return false;
}
}
And the following constructor:
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
I'm trying to get user from datebase but it is not working at all, i already tried many things, checked my syntax multiple times but i can't find my mistake. Anybody has an idea?
Edit: Changed code and added log but the log doesent report anything.

I can't count results in my database with PDO

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

retrieve values mysqli_fetch

I'm trying to get the id value from a table called usuario in the database, passing $username as parameter, the function $conexion->connect() returns a mysqli object. The functions give me no errors but it doesn't return the value from database. Am I missing something? or making any mistake.
Thanks for help.
public function checkUserNameExists($username){
$conexion = new Connection();
$conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conexion->connect()->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
This is the function connect() what is located in a class file "Connection"
public function connect(){
$mysqli = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli
}
public function checkUserNameExists($username){
$conexion = new Connection();
$conn = $conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conn->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
You should store the return value of new mysqli in a variable, and then use that variable to make queries or prepares from.

Function returns boolean not string

What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();

Categories