Use PHP to $_GET[ID] from URL - php

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.

Related

PHP MYSQL SELECT query parameter includes an ampersand(&)

I am using PHP PDO prepared statements. I am passing in a string and returning the record from MYSQL. I am passing three variables to the method.
The query returns nothing. If I perform the same query in phpmyadmin it returns all the correct data. I believe it is the ampersand(&) in the $team variable but, don't know I to work around it. I am not using a link and it is not a form element. It is a straight call to the method.
The values of the three parameters are
$season = '2018-19';
$league = 20;
$team = "Texas A&M University-Kingsville";
Here is my method:
public static function getTeamGames($season, $league, $team){
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season &&
league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $team, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
$weeklyGames = Game::getTeamGames( $season, $league, $tName );
I really appreciate the help of everyone.
Thank you in advance.
I was able to fix the issue.
I had to use html_entity_decode on the $team parameter.
I changed my method to the following:
public static function getTeamGames($season, $league, $team){
$dTeam = html_entity_decode($team);
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season && league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $dTeam, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}

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.

PHP OOP - Sending simple message and insert it to database

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

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