PHP set values from database - php

I am new and still lerning php and Im trying to set values that Im retrieving from postgresql database, but Im having problems with my code that i cant figure out and I hope someone here can help me. :)
This is the code:
public function __construct($username, $password)
{
$config = new Config();
$dbconn = pg_connect($config->getDbDsn()); // getDbDsn contains all the information that is needed to connect to the database.
$query = "SELECT username, password, id FROM user.member WHERE username = '$username'";
$result = pg_query($dbconn, $query);
$db = pg_fetch_all($result);
if($db)
{
foreach($db as $d)
{
if( $d['username'] == $username && $d['password'] == $password)
{
$this->verified = true;
$this->id = $d['id']; //save id does not work
$this->user = $d['username']; // save username does not work
}
else
{
$this->verified = false;
}
}
}
else
{
$this->verified = false;
}
}
Okay, this is what im trying to do. First im asking the database to give me the informationen from the table, that is a match to my users username and password. I am using a bool (verified) to verify the user. That works fine. But then, when Im trying to set the values of username and id for my user, that is impossible. If im creating a set_val-function (just to test my code, to try to find my error):
private $a = "";
private function set_val($data){ $this->a = $data; }
and I use that function to set value, in my construct-function:
$this->set_val('hello');
that works fine, until I put that function in my if($db)-statment, then it doesnt work anymore. (it works fine if I put it outside my if($db)-statement, like directly under $db = pg_fetch_all($result);).
$db = pg_fetch_all($result);
$this->set_val('hello'); // This works fine
if($db)
{
$this->set_val('hello'); // This does not work at all
foreach($db as $d)
$this->set_val('hello'); // And not this
}
For my get_val I have this code:
public function get_val(){
return $this->a;
}
(I also have the same get-functions for id and username)
And here Im trying to echo my value, which works fine, if I put the set_val-function outside my if-statement (and foreach-statement):
public function echo_val(){
echo $this->get_val();
}

Related

Undefined index error when trying to echo values, I am using functions outside of the class

Hey guys I have a question and I still consider myself pretty new at coding, so forgive me if I come off foolish.
I am studying in school as of now and we have a project to build a full stack recreation of craigslist. Any who the problem I am having deals with PHP. I have created an account page with text areas. I would like to echo out the user's information on their so the user can see what he put on and update as he likes. Since my navbar is included on every page, I added the code:
if(isset($_SESSION['logged_in_user'])){
var_dump($_SESSION['logged_in_user']);
$user = $_SESSION['logged_in_user'];
var_dump($user);
}
on my account page I figured I can echo it out as
<?= $attributes['first_name']?> within the placeholders. But I keep getting:
Undefined index: first_name
Also when I var_dump($user) I get an protected $attributes array.
In My Auth class is where I first defined $user as such:
public static function attempt($attemptedUsername, $attemptedPassword) {
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
and my findByUserName function is in the user class. the code is:
public static function findByUserName($user_name){
// Get connection to the database
self::dbConnect();
$stmt = self::$dbc->prepare('SELECT * FROM users WHERE user_name = :user_name');
$stmt->bindValue(':user_name', $user_name , PDO::PARAM_STR);
//execute gets its own line, t or false
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
// #TODO: Create select statement using prepared statements
// #TODO: Store the result in a variable named $result
// The following code will set the attributes on the calling object based on the result variable's contents
$instance = null;
if ($result) {
$instance = new static($result);
}
return $instance;
}
Your problem seems to be with not being able to access the variable $user outside of the static method attempt() this can be fixed by declaring the variable globally at the beginning of the method attempt() like this:
public static function attempt($attemptedUsername, $attemptedPassword) {
global $user;
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
More information can be found on this in the PHP documentation here.

wierd behaviour of unset php

I am developing an e-commerce website on which i need to store sessions inside database.I did that by implementing SessionHandlerInterface Class that is provided by the php itself.However it works totally fine and did store sessions inside the database , as well as read them properly.
However I am facing problem when I am using unset to unset a session variable.Sometimes it does work.Sometimes it doesn't.
For example:If i have a session variable by the name ABC unset might delete it from the database or it doesn't deletes the variable.
<?php
//inc.session.php
require_once 'RemoteAddress.php';
class SysSession implements SessionHandlerInterface
{
private $remote_write;
private $remote_read;
private $link;
private $ip_address_write;
private $ip_address_read;
public function open($savePath, $sessionName)
{
$link = new mysqli("localhost","root","","cakenbake");
if($link){
$this->link = $link;
return true;
}else{
return false;
}
}
public function close()
{
mysqli_close($this->link);
return true;
}
public function read($id)
{
$this->remote_read=new RemoteAddress();
$this->ip_address_read=$this->remote_read->getIpAddress();
$stmt=$this->link->prepare("SELECT `Session_Data`,`ip_address` FROM Session WHERE `Session_Id` = ? AND `Session_Expires` > '".date('Y-m-d H:i:s')."'");
$stmt->bind_param("s",$id);
$stmt->execute();
//$result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
/*$result=$this->link->prepare("Some query inside")
* This shows up an error stating prepare method not found
*
*/
$res=$stmt->get_result();
if($row=$res->fetch_assoc()){
if($this->ip_address_read==$row['ip_address'])
return $row['Session_Data'];
else return "";
}else{
return "";
}
}
public function write($id, $data)
{
$this->remote_write=new RemoteAddress();
$this->ip_address_write=$this->remote_write->getIpAddress();
if(!empty($data))
{
$DateTime = date('Y-m-d H:i:s');
$NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
$stmt=$this->link->prepare("REPLACE INTO Session SET Session_Id = ?, Session_Expires = '".$NewDateTime."', Session_Data = '".$data."', ip_address = '".$this->ip_address_write."'");
$stmt->bind_param("s",$id);
// $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
public function destroy($id)
{
$stmt = $this->link->prepare("DELETE FROM Session WHERE Session_Id =?");
$stmt->bind_param("s",$id);
if($stmt->execute()){
return true;
}else{
return false;
}
}
public function gc($maxlifetime)
{
$result = $this->link->query("DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < UNIX_TIMESTAMP(NOW()))");
if($result){
return true;
}else{
return false;
}
}
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>
The above code stores and read sessions from the database.
Structure of the session table.
What could be the possible reason for this weird behaviour. Do i have to implement unset function as well?.
How should i resolve this problem?
If you could suggest me someother already written code for storing in database.That would work as well but i dont need any frameworks such as codeigniter and Yii2.
If you need more information regarding this problem.I will update my question.
Thanks in advance!
The problem is not with the unset function but with your write function.The write function is responsible for any updates that are made to the specific session id.
The wierd behiviour is not with the unset but it is with the write funciton you have implemented.
See ,the !empty constraint checks if your data is empty or not.What i can guess is that your database for that specific id must be empty after the removal of the specific variable .So the write tries to update your row with an empty value but with that constraint it isn't able to do so.
Just remove the !empty tag and it will work like a charm.

Catching the returned value

this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.

Switching from mysql to mysqli issues

Below is some code that works fine, however it used mysql_* and i dont want that anymore. I have tried to redo this section in mysqli but it's not working. I can post my entire code if you wish, but i am certain i know where the issue lies. Below is the code:
Old:
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT client_id FROM clients WHERE client_email_address = '{$this->_username}' AND client_password = '{$this->_pass_sha1}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
New:
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows)
{
list($this->_id) = #array_values($data->fetch());
return true;
}
else
{
return false;
}
}
I'm still learning mysqli and not quite ready for PDO stuff as i found that a little confusing. As i say, this whole script works perfectly with mysql_* but not so much with mysqli. When i try and log in my form doesnt display any errors nor does it push forward to the next page, so i know its this bit that is the issue
it is advised to use a helper function, either with old mysql or modern mysqli
public function verifyDatabase()
{
$sql = "SELECT client_id FROM clients WHERE email = ? AND password = ?";
return $this->db->getOne($sql ,$this->_username,$this->_pass_sha1);
}
Also note that dbConfig.php should not be included in the every method but, but only once. While DB handler should be assigned to a class variable in the constructor.
Change your code to this. I'm not saying it will fix problems but will be better.
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows > 0)
{
$result = $data->fetch();
$this->_id = $result['client_id'];
return true;
}
else
{
return false;
}
}
You can also put var_dump($result); after the $result = $data->fetch(); line to print out what exactly is being returned.

Can't pass mysqli object to class in PHP

So I'm working on a simple user class in php, which has a class variable which contains the mysqli object, however I keep getting the error:
Fatal error: Call to a member function real_escape_string() on a non-object in */classes/user.php on line X
I've checked everything, it should work, but it doesn't. Somehow. This is my code:
namespace bibliotheek;
class user
{
private $mysql;
private $logged_in = false;
private $user_data = null; //ARRAY: user_id, e-mail, password, bevoegdheid, naam, achternaam, adres, postcode, stad
function __construct(\mysqli $mysql, $salt)
{
$this->mysql = $mysql;
}
public function login($email, $pass, $hash = false)
{
$email = $this->mysql->real_escape_string($email);
if($hash == false)
$pass = sha1($this->salt.$pass);
$query = "SELECT *
FROM gebruikers
WHERE gebruikers.email = '$email' AND gebruikers.password = '$pass'";
$result = $this->mysql->query($query);
$user_data = $result->fetch_assoc();
if($user_data == null)
return;
$this->logged_in = true;
$this->user_data = $user_data;
$this->create_cookies($email, $pass);
}
}
And this is how the mysqli object gets passed to the class:
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
$user = new bibliotheek\user($mysql, $cfg['salt']);
the mysql login data is correct, I've made sure of that.
I must be missing something really obvious here, but I just can't see it. Any help is greatly appreciated. Thanks!
And this is how it should be
error_reporting(E_ALL);
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
if ( !$mysql )
{
throw new Exception(mysqli_connect_error()));
}
$user = new bibliotheek\user($mysql, $cfg['salt']);
I'm really f-ing stupid, I compacted my code a bit when I posted it on here and I left out this part:
$this->mysql = $mysql;
$this->mysql = $salt;
Kill me now.

Categories