PHP OOP - Sending simple message and insert it to database - php

I wrote a PHP script for myself which gets data from a form and simply send it to a database. It looks like this:
class Users {
/* Deklarovanie premennych */
public $name = null;
public $email = null;
public $phone = null;
public $message = null;
public function __construct( $array = array() ) {
if( isset( $data['name'] ) ) $this->name = stripslashes( strip_tags( $data['name'] ) );
if( isset( $data['email'] ) ) $this->email = stripslashes( strip_tags( $data['email'] ) );
if( isset( $data['phone'] ) ) $this->phone = stripslashes( strip_tags( $data['phone'] ) );
if( isset( $data['message'] ) ) $this->message = stripslashes( strip_tags( $data['message'] ) );
/* využitá funkcia stripslashes pre odstránenie "\" ktoré mohol vložiť užívateľ do formulara */
}
public function storeFormValues( $formvalues ) {
$this->__construct( $formvalues );
/*uložíme hodnoty zíaskne z $_POST*/
}
public function message() {
$correct = false;
try {
$db_con = new PDO( DB_HOST, DB_USER, DB_PASS );
$db_con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO user(name, email, phone, message) VALUES(:name, :email, :phone, :message)";
$stmt = $db_con->prepare( $sql );
$stmt->bindValue( "name", $this->name, PDO::PARAM_STR );
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->bindValue( "phone", $this->phone, PDO::PARAM_STR );
$stmt->bindValue( "message", $this->message, PDO::PARAM_STR );
$stmt->execute();
return "Správa bola úspešne odoslaná!! <br/> <a href='index.php'>pozrieť správy!</a>";
}catch( PDOException $exce ) {
return $exce->getMessage();
}
}
}
?>
In my eyes the code looks fine and understandable. It doesn't throw any errors but the problem is that it doesn't insert anything into the database. I am not sure where the problem can be.
And I nearly forgot this is my index part:
<?php
} else {
$Users = new Users;
$Users->storeFormValues( $_POST );
if( $Users->message() ) {
echo "Sprava bola úspešne odoslana";
} else {
echo "Sprava nebola odoslana";
}
}
?>

Related

Custom session handler in PHP 7 using mysql

I already have read all about Sessions in PHP on stackoverflow but it haven't help. I have session class that was working on PHP 5.X, and I haven't been programing since.
I have been started about month ago again with PHP, but my session handler is invalid.
Please, can you help me?
<?php
<?php
/*
CREATE TABLE IF NOT EXISTS `sessions` (
`se_id` varchar(50) NOT NULL DEFAULT '',
`se_value` mediumblob,
`se_expires` int(11) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `sessions`
ADD PRIMARY KEY (`se_id`), ADD KEY `se_id` (`se_id`,`se_expires`);
*/
define( "MAXLIFETIME", 86400 );
define( "DSN", "mysql:host=localhost;dbname=demo" );
define( "DB_USER", "root" );
define( "DB_PASS", "whatever..." );
final class MYSession{
protected $_table_name = 'sessions';
protected $_primary_key = 'se_id';
protected $_where = array();
protected $_order_by = 'se_id';
protected $data = array( "se_id" => "",
"se_value" => "",
"se_expires" => ""
);
public $se_id;
public $se_id_old;
public $db;
private $sessionName;
//public $maxlifetime = get_cfg_var("session.gc_maxlifetime");
public $maxlifetime;
private $path;
private $domain;
private $secure;
private $httponly;
public function setParams(){
ini_set( 'session.gc_probability', 1 ) ;
ini_set( 'session.gc_divisor', 100 );
ini_set( "session.use_only_cookies", TRUE );
ini_set( "session.use_trans_sid", FALSE );
ini_set( "session.use_only_cookies", "1" );
ini_set( "session.entropy_file", "1" );
}
public function startSession( $sessionName, $maxlifetime = FALSE, $path = FALSE, $domain = FALSE, $secure = FALSE, $httponly = FALSE ){
$this->setParams();
if( $maxlifetime ){ $this->maxlifetime = $maxlifetime; }
else{ $this->maxlifetime = 0; }
if( $path ){ $this->path = $path; }
else{ $this->path = "/"; }
if( $domain ){ $this->domain = $domain; }
else{ $this->domain = NULL; }
if( $secure ){ $this->secure = $secure; }
else{ $this->secure = isset( $_SERVER[ 'HTTPS' ] ); }
if( $httponly ){ $this->httponly = $httponly; }
else{ $this->httponly = TRUE; }
$this->setSessionCookieData();
$this->sessionName = $sessionName;
session_name( $this->sessionName );
session_set_save_handler(
array( $this, "open" ),
array( $this, "close" ),
array( $this, "read" ),
array( $this, "write" ),
array( $this, "destroy" ),
array( $this, "gc" )
);
session_start();
session_regenerate_id( TRUE );
$this->se_id = session_id();
$this->gc( $this->maxlifetime );
return $this->se_id;
}
public function setSessionCookieData(){
return session_set_cookie_params( $this->maxlifetime, $this->path, $this->domain, $this->secure, $this->httponly );
}
public function getSessionCookieData(){
$sessionCookieDataArray = array();
$sessionCookieDataArray = session_get_cookie_params( );
return $sessionCookieDataArray;
}
//---------------------------------------------------------------------------------------------------
public function __destruct(){ session_write_close(); }
public function newSessid(){ return $this->se_id; }
public function oldSessid(){ return $this->se_id_old; }
public function open( $path, $se_id ){
try{
$this->db = new PDO( DSN, DB_USER, DB_PASS );
$this->db->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $error ){ echo 'Error: '.$error->getMessage(); }
return TRUE;
}
public function close(){
$this->db = "";
return TRUE;
}
public function read( $se_id ){
$sql = "SELECT se_value FROM ". $this->_table_name. " WHERE se_id = :se_id";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->execute();
$result = $statement->fetch( PDO::FETCH_ASSOC );
}
catch( PDOException $error ){ die( "Unable to access to database read1" ); }
if( !empty( $result[ "se_value" ] ) ){
$sql = "UPDATE ". $this->_table_name. " SET se_expires = UNIX_TIMESTAMP( UTC_TIMESTAMP() ) WHERE se_id = :se_id";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->execute();
}
catch( PDOException $error ){ die( "Unable to access to database read2" ); }
}
return $result[ "se_value" ];
}
public function write( $se_id, $se_val ){
$sql = "SELECT * FROM " . $this->_table_name . " WHERE se_id = :se_id AND se_value = :se_val";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->bindValue( ":se_val", $se_val, PDO::PARAM_STR );
$statement->execute();
if( $statement->fetch() ){
$sql= "UPDATE ". $this->_table_name. " SET se_value = :se_val, se_expires = UNIX_TIMESTAMP( UTC_TIMESTAMP()) WHERE se_id = :se_id";
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->bindValue( ":se_val", $se_val, PDO::PARAM_STR );
$statement->execute();
}
else{
$sql = "INSERT INTO ". $this->_table_name. " ( se_id, se_value, se_expires ) VALUES( :se_id, :se_val, UNIX_TIMESTAMP( UTC_TIMESTAMP()) )";
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->bindValue( ":se_val", $se_val, PDO::PARAM_STR );
$statement->execute();
}
}
catch( PDOException $error ){ die( "Unable to insert or update database" ); }
}
public function destroy( $se_id ){
$sql = "DELETE FROM ". $this->_table_name. " WHERE se_id = :se_id";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$control_var= $statement->execute();
}
catch( PDOException $error ){ die( "Unable to destroy data in database" ); }
$this->gc( $this->maxlifetime );
return ( $control_var );
}
public function gc( $maxlifetime ){
$sql = "DELETE FROM ". $this->_table_name. " WHERE UNIX_TIMESTAMP( UTC_TIMESTAMP() ) - se_expires > :maxlifetime";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":maxlifetime", $this->maxlifetime, PDO::PARAM_INT );
$control_var = $statement->execute();
}
catch( PDOException $error ){ die( "Unable to select from database_" ); }
return ( $control_var );
}
public function regenerateId( ){
$this->gc( $this->maxlifetime );
$old_sessid = $this->se_id;
session_regenerate_id( TRUE );
$new_sessid = session_id();
$sql = "UPDATE ". $this->_table_name. " SET se_id = :new_sessid WHERE se_id = :old_sessid";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":new_sessid", $new_sessid, PDO::PARAM_STR );
$statement->bindValue( ":old_sessid", $old_sessid, PDO::PARAM_STR );
$control_var = $statement->execute();
$this->se_id = $new_sessid;
$this->se_id_old = $old_sessid;
}
catch( PDOException $error ){ die( "Unable to select from database_REGID" ); }
return $new_sessid;
}
//---------------------------------------------------------------------------------------------------
public function destroySession(){
if( ini_get( "session.use_cookies" ) ){
$params = session_get_cookie_params();
setcookie( $this->sessionName, '',
time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
$_SESSION[ $this->sessionName ] = array();
unset( $_SESSION[ $this->sessionName ] );
session_unset( $this->sessionName );
session_destroy();
}
public function generateSessionName( $brojZnakova ){
return substr( $this->generateId(), 0, $brojZnakova );
}
//---------------------------------------------------------------------------------------------------
public function generateId(){ //private
$salt = 'x7^!bo3p,.$$!$6[&Q.#,//#i"%[X';
$random_number = mt_rand( 0, mt_getrandmax() );
$ip_address_fragment = md5( substr( $_SERVER['REMOTE_ADDR'], 0, 5 ) );
$timestamp = md5( microtime( TRUE ).time() );
$hash_data = $random_number . $ip_address_fragment . $salt . $timestamp;
$hash = hash( 'sha256', $hash_data ); //'sha256', 'haval160,4', 'md5'
return trim( $hash );
}
}
$newSession = new MYSession();
$newSession->setParams();
$newSession->startSession( 'newSession' );
?>

PHP: How to use string variable as table in sql query (PDO)

I would like to make a general function to select last inserted id's of different tables.
I already tried multiple things, this might be the best effort (in db.inc.php);
<?php
define( 'DB_HOST', 'localhost' );
define( 'DB_NAME', 'modlar' );
define( 'DB_USER', 'root' );
define( 'DB_PASS', 'password' );
function verbinden(){
$verbinding = 'mysql:host=' . DB_HOST . ';DB_NAME=' . DB_NAME;
$db = null;
try{
return new PDO( $verbinding, DB_USER, DB_PASS );
}catch( PDOException $e ){
return NULL;
}
}
function loopdoor( $naam, $ding){
$regels = '';
if( is_array($ding) || is_object($ding)):
$wat = (is_array($ding)? 'array' : 'object');
$regels .= '<strong>'.$naam.'['.$wat.']</strong><ul>';
foreach( $ding as $k => $v):
$regels .= loopdoor( $k, $v);
endforeach;
$regels .= '</ul>';
else:
$regels .= '<li><strong>'.$naam.'</strong> => '.$ding.'</li>';
endif;
return $regels;
}
function last_id( &$db , $table, $column){
if( is_null( $db ) ) return array();
$sql = "
SELECT
max(modlar.table.column)
FROM
modlar.table";
$vraag = $db->prepare( $sql );
$vraag->bindValue( ':table', $table, PDO::PARAM_STR );
$vraag->bindValue( ':column', $column, PDO::PARAM_STR );
$vraag->execute();
return $vraag->fetchAll( PDO::FETCH_OBJ );
}
Where modlar is my database. And my variables (in db.php);
<?php
require_once 'db.inc.php';
// Verbinden met database
$db = verbinden();
if( is_null($db))
die('<h1>Error</h1>');
echo 'done';
$table = 'time';
$column = 'time_id';
$last = last_id($db, $table, $column);
echo '<ul>'.loopdoor('all data', $last).'</ul>';
?>
But I dont get any data on my screen (and no error). However, when I add the variables directly to the code, I'll get the last id of that table. So like;
$sql = "
SELECT
max(modlar.time.time_id)
FROM
modlar.time";
What is going wrong?

Error: 'Trying to get property of non-object'

So i'm having this trouble. Errors on lines 3,4,5. This is how i define object properties:
class Article {
//line 3
public $id; // line 4
public $pubDate; // line 5
public $title;
public $content;
And here is my method that gives an error:
public static function getById( $id ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *, UNIX_TIMESTAMP(pubDate) AS pubDate FROM material WHERE id = :id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $id, PDO::PARAM_INT );
$st->execute();
$row = $st->fetch();
$conn = null;
if ( $row ) return new Article( $row );
}
I've tried to disable error by using:
error_reporting(0);
#ini_set('display_errors', 0);
But it's only masks the problem, publication still doe's not appear on page.
Thank you.
This is function constructor:
public function __construct($data = array()) {
if ( isset( $data['id'] ) ) $this->id = $data['id'];
if ( isset( $data['pubDate'] ) ) $this->pubDate = $data['pubDate'];
if ( isset( $data['title'] ) ) $this->title = $data['title'];
if ( isset( $data['content'] ) ) $this->content = $data['content'];
}
And function that calls getById method:
function viewArticle() {
if ( !isset( $_GET["articleId"] ) || !$_GET["articleId"] ) {
homepage();
return;
}
$results = array();
$results['article'] = Article::getById( (int) $_GET["articleId"] );
$results['pageTitle'] = $results['article']->title;
require( TEMPLATE_PATH . "/viewArticle.php" );
}
Solution has been found. Problem was - my stupidity.
Best regards for all who guided me and responded to my plea for help.

Use PHP to $_GET[ID] from URL

i am using simple code to get some data from DB based on some unique ID called VIN.
i wrote a script which work fine if somebody insert it in form, but now i need to edit to work more automaticly, and use $_GET['vin'] from URL and just display results based on that.
My try of code looks like:
public $vin = null;
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function fetchByVinEvidence($vin) {
$success = false;
try{
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM evidence_vin WHERE vin = :vin LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
$stmt->execute();
echo "<table>";
echo "<th>First Registration</th>";
echo "<th>Validity Until</th>";
echo "<th>Rpm</th>";
echo "<th>Max-Speed</th>";
echo "<th>Action</th>";
while ($row = $stmt->fetch()){
echo "<tr>";
echo "<td>24</td>";
echo "<td>".$row['claim_number']."</td>";
echo "<td>".$row['license']."</td>";
echo "<td>".$row['country']."</td>";
echo "<td>".$row['vin']."</td>";
echo "</tr>";
}
echo "</table>" ;
}catch(PDOExeption $e){
echo $e->getMessage();
echo $con->errorInfo();
}
return $success;
}
and call the function:
$vin = $_GET['vin'];
echo $vin;
$data = new Data;
$data->fetchByVinEvidence($vin);
Can somebody help me with that?
You pass a variable $vin to the function fetchByVinEvidence but then use the class level variable $this->vin instead of the passed one.
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
should be
$stmt->bindValue( "vin", $vin, PDO::PARAM_STR );
OR set the class level variable to the passed one at the start of the function if you need to use it elsehwere:
public function fetchByVinEvidence($vin) {
$this->vin = $vin;
....
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
__construct if waiting for an array, give it your $_GET directly :
$data = new Data($_GET); // and not $_GET['vin'] as it was the case before my edit
$data->fetchByVinEvidence($vin);
It was giving null because you didn't send anything to your constructor, so it used the default value : an empty array.

PHP Error: Call to a member function storeFormValues() on a non-object

I have an error and I don't know what I am doing wrong. Help, please, with this :)
So, I have a class named Activities and in it a I have few functions as here:
class Activities
{
public $content = null;
public function __construct( $data=array() ) {
if ( isset( $data['content'] ) ) $this->content = $data['content'];
}
public function storeFormValues ( $params ) {
$this->__construct( $params );
}
public static function getData() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM exceptions WHERE name = 'atrakcje'";
$st = $conn->prepare( $sql );
$st->execute();
$row = $st->fetch();
$conn = null;
if ( $row ) return new Activities( $row );
}
public function update() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE exceptions SET content=:content WHERE name = 'atrakcje'";
$st = $conn->prepare ( $sql );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->execute();
$conn = null;
}
}
And I have a function editActivities() in my little Admin Panel I made:
function editActivities() {
$results = array();
$results['pageTitle'] = "Edytuj Atrakcje";
$results['formAction'] = "editActivities";
if ( isset( $_POST['saveChanges'] ) ) {
$activities->storeFormValues( $_POST );
$activities->update();
header( "Location: admin.php?action=editActivities&status=changesSaved" );
} elseif ( isset( $_POST['cancel'] ) ) {
header( "Location: admin.php?action=editActivities" );
} else {
$results['activities'] = Activities::getData();
require( TEMPLATE_PATH . "/admin/editActivities.php" );
}
}
Also I have a HTML Form to make changes. But when I submit filled form I get an error:
Fatal error: Call to a member function storeFormValues() on a non-object in C:\xampp\htdocs\admin.php on line 285
285 line in my code is here:
if ( isset( $_POST['saveChanges'] ) ) {
$activities->storeFormValues( $_POST );
$activities->update();
I don't know what's going on. I have just the same code to edit other Articles and Users and I can't figure out what's bad here. Thanks for your help!
$activities is not instantiated, so you can't call one of its instance methods. You ought to instantiate it with
$activities = new Activities($_POST);
Also, in your static function getData you either return an Activities or NULL, depending on the value of $row. But this may make $results['activities'] sometimes an object and sometimes not, which is tricky to handle and might result in the same error being raised again.
add
$activities = new Activities();
$activities->storeFormValues( $_POST );
....

Categories