i am having some problem with my code, i try to simple insert some logs when user use search on my site.
Log should contains:
date in unix time -> using function for it
username -> its stored in Session
vin -> its string he post in input field
Top of the class
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 );
}
function code:
public function logFromSearch() {
$correct = false;
//$this->username = $_SESSION]['username'];
$date = new DateTime();
try {
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO logs(date, user, vin) VALUES(:date, :user, :vin)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "date", $date->getTimestamp(), PDO::PARAM_STR );
$stmt->bindValue( "user", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
echo $this->vin;
echo $date->getTimestamp();
$stmt->execute();
return "Everything is OKEY";
} catch( PDOException $e ) {
return $e->getMessage();
}
}
Its not importing anything to database dispite the fact it should in my opinion. I try to debug it so i found out my way of adding username from session is not possible way and also find out that this->vin and $date->getTimestamp() is returning actual data which it should insert to database so can somebody help me to find where is the problem? (in same class i am using other function for database connection and they work find so its not in setting up connecting / db name and host and so on because its in different file)
P.S. Errors : I dont get any errors just single notice Notice: Undefined property: Data::$username which is understandable.
Related
I have a question that, I would have thought has definitely been asked before so excuse me if I am phrasing it wrong but I was unable to find it. The question requires a few separate snippets of code to address. I have an application that we use to review the validity of leads submitted to our client from certain forms for billing purposes. What I am wanting, is for when the user presses the button "valid" or "invalid", it assigns the lead the proper status and removes it from the currently displayed table, which would be leads that 'need review'. These leads have a needsreview value of 'null', which is defaulted. The other leads are assigned an appropriate value of 1 or 0 upon the button press.
That all works, the only thing I cannot figure out is how to not redirect the user to restart the search on click. I just want it to remove the record from what is currently displayed. Here is a few pieces of the code, I would greatly appreciate any help. Again, it all works, just in not the most convenient way and I am not sure how to do it the better way, I just need someone more experienced to point me in the right direction.
Here is the buttons code:
<td style="background:#fff;border:none;">
<button style="margin-bottom:2.5%;margin-top:2.5%;background:#2ECC71;border-radius:5px;width:175px;height:30px;border:3px solid #3FC380;color:#fff;font-weight:bold;" onclick="location='admin.php?action=validCustomer&customersId=<?php echo $customers->id?>'">Valid</button>
</td>
<td style="background:#fff;border:none;">
<button style="margin-bottom:2.5%;margin-top:2.5%;background:#2ECC71;border-radius:5px;width:175px;height:30px;border:3px solid #3FC380;color:#fff;font-weight:bold;" onclick="location='admin.php?action=invalidCustomer&customersId=<?php echo $customers->id?>'">Not Valid</button>
</td>
Here is the other relevant code:
function searchIsValid() {
$results['formAction'] = "searchIsValid";
$results['pageTitle'] = "Search By Validation Status";
require (TEMPLATE_PATH . "/admin/searchIsValid.php" );
}
function validCustomer(){
if (!$customers = customers::getById( (int)$_GET['customersId'] ) ){
echo "Error getting customer ID";
}
$results['formAction'] = "validCustomer";
$results['pageTitle'] = "Lead Validated";
$customers->validCustomer($_SESSION['username']);
header( "Location: admin.php?action=searchIsValid" );
}
function invalidCustomer(){
if (!$customers = customers::getById( (int)$_GET['customersId'] ) ){
echo "Error getting customer ID";
}
$results['formAction'] = "invalidCustomer";
$results['pageTitle'] = "Lead Invalidated";
$customers->invalidCustomer($_SESSION['username']);
header( "Location: admin.php?action=searchIsValid" );
}
And finally, the last piece of relevant code, the SQL part:
public function update() {
// Does the customer object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "customers::update(): Attempt to update a customer object that does not have its ID property set.", E_USER_ERROR );
// Update the customer
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE leads SET valid=:valid WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
public function validCustomer($username) {
// Does the customer object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "customers::update(): Attempt to update a customer object that does not have its ID property set.", E_USER_ERROR );
// Update the customer
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// if invalid
$sql = "UPDATE leads SET valid=1, reviewedby='$username' WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
public function invalidCustomer($username) {
// Does the customer object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "customers::update(): Attempt to update a customer object that does not have its ID property set.", E_USER_ERROR );
// Update the customer
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// if invalid
$sql = "UPDATE leads SET valid=0, reviewedby='$username' WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
I think this is all the relevant code but, I probably forgot some so feel free to remind me, and thanks again for taking the time to read my post and offer assistance!
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.
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 );
....
I'm in the process of learning to use OOP in php, I'm having a few issues with what is probably a really simple solution that I'm just not using the right search terminology to find.
I have my class
class user {
function getUser() {
if ($_SESSION['status'] == "authorized") {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username = :username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $_SESSION['usernames'], PDO::PARAM_STR );
$st->execute();
$row = $st->fetch();
$conn = null;
return $row;
}
}
}
and then in my template file i'm calling the following
$user = new user();
echo $user->getUser->icon;
hopefully the bottom line shows what i'm trying to call, basically in the sql results I'm after just calling $row['icon']; directly from the return array.
is this possible? if so could someone point out the terminology i'm missing
Thanks in advance
If you are going to keep using that object I would do the following:
class user {
public $icon;
function getUser() {
if ($_SESSION['status'] == "authorized") {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username = :username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $_SESSION['usernames'], PDO::PARAM_STR );
$st->execute();
$row = $st->fetch();
$conn = null;
$this->icon=$row;
}
}
}
Then you can use:
echo $user->icon;
Try the following :
print_r ($user->getUser);
If that returns an array, try it like this :
echo $user->getUser['icon'];
You should use it this way:
$userobj = new User();
$user = $userobj->getUser();
Now you have the fetched data in the $user variable and may output it at will:
echo $user['icon'];
My example should work with your existing code, and if you want to change the values in the future of the users, you just change the key in the echo statement: echo $user['someothervalue'];
I've recently started working with mysqli.
Previously with php and MySQL I would write a common class holding the MySQL database connection as I don't want to repeat that code over and over.
Now with mysqli I can't seem to do this.
Is there a simple way to do this I think I'm missing something really obvious.
Have you considered using PDO?
Example:
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
$user_id = 1;
try
{
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e )
{
exit( "Error connecting to database: " . $e->getMessage() );
}
$statement = $db->prepare( "SELECT * FROM user WHERE user_id=:user_id" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user_id', $user_id, PDO:: PARAM_INT );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );