Trying to get property of non-object error in PHP - php

I'm trying to save my data using php. This is how I tried:
<?php
session_start();
if(!isset($_SESSION["MemberID"])) header("Location:logout.php");
include '../config.php';
include '../momdb.php';
$page_title = "Customers";
$mode = "Save";
$db = 'db';
$showmessage = false;
$message = "";
if (isset ( $_POST ["btnSave"] )) {
$data = new table ();
$data->MomID = $_POST ["CustomerID"];
$data->CustomerName = $_POST ["CustomerName"];
$data->FromDate = string_to_date ( $_POST ["FromDate"] );
$data->ToDate = string_to_date ( $_POST ["ToDate"] );
$data->CreatedBy = $_SESSION["MemberID"];
$data->CreatedDatetime = date ( "Y-m-d H:i:s" );
$data->LastModifiedBy = $_SESSION["MemberID"];;
$data->LastModifiedDatetime = date ( "Y-m-d H:i:s" );
$rows = array ();
if (intval ( $data->CustomerID) > 0) {
$rows = $db::Update ( $data );
} else {
$rows = $db::Save ( $data );
}
if (intval ( $rows ["WebID"] ) > 0) {
$date = new DateTime ();
header ( "Location: customerlist.php?msg=yes&msgt=s&t=" . $date->getTimestamp () . "&mtext=Record saved successfully" );
} else {
$showmessage = true;
$message = $rows ["Message"];
}
} elseif (isset ( $_GET ["CustomerID"] )) {
$data = $db::GetByID ( $_GET ["CustomerID"] );
if ($data == false) {
$data = new table ();
$data->CustomerID = 0;
}
}
if ($data->CustomerID == "0")
$mode = "Save";
else
$mode = "Update";
?>
This code is for sending my values to the db page for saving them in the DB. I've used the PDO method. This is the first time I'm saving the record this way. That's why there is lots of confusion. The following code shows the Save() method, which I used to save the values to the DB.
public function Save(table $customer) {
$data = new DB ();
$stmt = $data->connection->prepare ( "CALL proc_CreateCustomer (:CustomerName, :FromDate,:ToDate,:CreatedBy, :CreatedDatetime, :LastModifiedBy, :LastModifiedDatetime)" );
$stmt->bindParam ( ':CustomerName', trim ($customer->CustomerName ));
$stmt->bindParam ( ':FromDate', $customer->FromDate );
$stmt->bindParam ( ':ToDate', $customer->ToDate);
$stmt->bindParam ( ':CreatedBy',$customer->CreatedBy );
$stmt->bindParam ( ':CreatedDatetime', $customer->CreatedDatetime );
$stmt->bindParam ( ':LastModifiedBy',$customer->LastModifiedBy );
$stmt->bindParam ( ':LastModifiedDatetime', $customer->LastModifiedDatetime );
$stmt->execute ();
$record = $stmt->fetch ( PDO::FETCH_OBJ );
if ($record == false) {
return array (
"WebID" => 0,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
} else {
return array (
"WebID" => $record->CustomerID,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
}
}
This is how I've tried. But, whenever I try to save the details, it shows: " Trying to get property of non-object in D:\Workspace\Application\momdb.php on line 39", ie it shows error in the line "Message" => $record->Message,"AppID" => $customer->AndroidID. I don't what's wrong with this. Can someone tell me what should I change so that it work fine?

if ($record == false) {
return array (
"WebID" => 0,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
}
In this piece of code $record is false(y), so $record->Message doesn't exist.

Related

zend framework Creating default object from empty value

im trying to modify a code, when i submit the form im getting this error "Creating default object from empty value". I make n echo statment in $request->isPost is not echoing. this my code below
public function addAction() {
$report = new Report();
$request = $this->getRequest ();
$validateOnly = $request->isXmlHttpRequest ();
if ($validateOnly)
$this->setNoRenderer ();
$userObj = new User ( );
$userRow = $userObj->createRow();
$status = ValidationContainer::instance ();
$userArray = $userRow->toArray ();
$userArray['acls'] = User::getACLs ( $user_id ); //set acls
$this->viewAssignEscaped ( 'user', $userArray );
$locations = Location::getAll();
$this->viewAssignEscaped('locations', $locations);
//var_dump($locations); exit;
if ($request->isPost()) {
self::fillFromArray ( $userRow, $details );
$userRow->is_blocked = 0;
if ($id = $userRow->save ()) {
in the provider_code table.
$this->insertPlainPassword($this->getSanParam('password'), $id);
$status->setStatusMessage ( 'The new user was created.' );
$this->saveAclCheckboxes ( $id );
} else {
$status->setStatusMessage ( 'The user could not be saved.' );
}
}
}
}
i have been trying to resolve it for weeks now.
}

SQLite Prepared Statements not Inserting

I'm trying to insert into a database using PDO but after finishing the script and testing it out and I am not seeing any sort of input from inserting into the database, I've tried returning errors from PDO but nothing. I'm not sure what's happening
I've updated the parameter names and they do not seem to change anything with the result of the code. Seems the q() function is just having issues.
Database is initialized and looks like:
function __construct() {
if ( ! file_exists( dbpath . DB ) ) {
$this->db = true;
$this->open( dbpath . DB, SQLITE3_OPEN_CREATE|SQLITE3_OPEN_READWRITE ) or $this->db = false;
if ( $this->db == false ) {
return false;
}
$table = "CREATE TABLE link_hits( id INTEGER PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, hits INT NOT NULL, date_added datetime default current_timestamp)";
$this->exec($table);
} else {
$this->db = true;
$this->open( dbpath . DB, SQLITE3_OPEN_CREATE|SQLITE3_OPEN_READWRITE ) or $this->db = false;
if ( $this->db == false ) {
return false;
}
}
}
Prepared statement function
function q ( $q, $v ) {
if ( $this->db ) {
$this->securedb = $this->prepare( $q );
foreach ( $v as $k=>$vv ) {
if ( is_numeric( $vv ) ) {
$this->securedb->bindValue($k, $vv, SQLITE3_INTEGER);
} else {
$this->securedb->bindValue($k, $vv, SQLITE3_TEXT);
}
}
$this->errorInfo = $this->errorInfo();
return ( ( $this->handle = $this->execute() ) == true ) ? $this->handle : false;
}
return false;
}
Add link function
function addlink ( $link ) {
if ( $this->linkexists( $link ) ) {
return false;
}
$this->que = "INSERT INTO link_hits (link, hits) VALUES (:link, :hits)";
$this->input = array(
':link' => $link,
':hits' => 0
);
return ( $this->q( $this->que, $this->input ) ) ? true : false;
}
Am I not forming my statement correctly? I followed several tutorials. I'm really used to MySQL but will not have access to it where this will be. :(
Even my linkexists function throws a false. And yes, the link is there, I forced it in with a normal query.
function linkexists( $link ) {
$this->que = "SELECT link FROM link_hits WHERE type='table' AND link=':link'";
$this->input = array(
':link' => $link
);
return ( ( $this->handle = $this->q( $this->que, $this->input ) ) == true ) ? true : false;
}
Parameter names must not end with a semicolon:
$this->que = "INSERT ... VALUES (:link, :hits)";

PHP error fetching json file

Can someone help why my JSON file can't show? I beginner for JSON. This is my code, its only show blank document. I am learning this tutorial from this website http://contohprogramandroid.blogspot.com/2013/10/contoh-program-android-aplikasi-wisata.html. thank you so much.
this my image when running the code.
//this is the code webservice.php
<?php
class Database {
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "wisata_jogja";
private $conn;
// constructor
function __construct() {
try{
$this->conn = new PDO( "mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this->pass );
}catch( PDOException $e ) {
echo "error pdo $e";
}
}
public function showAllData( $table ) {
$sql ="SELECT * FROM $table";
$q = $this->conn->query( $sql ) or die( "Failed !!" );
while ( $r = $q->fetch( PDO::FETCH_ASSOC ) ) {
$data[] = $r;
}
return $data;
}
}
$database = new Database();
$response = array();
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
$response['location'] = array();
foreach ( $database->showAllData( 'lokasi' ) as $value ) {
$kode = array();
extract( $value );
$kode['id'] = $id;
$kode['nama'] = $nama;
$kode['alamat'] = $alamat;
$kode['gambar'] = $gambar;
$kode['lat'] = $lat;
$kode['lng'] = $lng;
array_push( $response['location'], $kode );
}
echo json_encode( $response );
}
?>
Your condition to output is this:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
Thus, the script won't output any JSON since condition is not met.
From your screenshot it is clear your are missing the GET parameters.
In your browser add the parameter to the url:
http://localhost/wisata/webservice.php?get=lokasi
It's always good to take alternative action when condition is not true.
You should always echo something just so you know what is going on:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
//..............
echo json_encode( $response );
}else{
echo "cannot output JSON data: parameter is missing!!;
}
Are you sure that you pass the GET variable "lokasi" to your script ?
Otherwise, it would not go through the if condition
if(isset($_GET['get'] ) && $_GET['get']=='lokasi')
You can check this by trying to dump the variable or any foobar data inside the if condition to verify your code goes that far, for instance :
if(isset($_GET['get'] ) && $_GET['get']=='lokasi') {
$response['location'] = array();
$myTest = array('test');
var_dump($myTest); // Should display something on screen
// The rest of your code here

PHP Regex String in Array

I would like to be able to set a global username like <anythinghere>#domain3.com as a username value in the $usernames array (in code below). This is so that I can then go and redirect users based on domain, having already been "authenticated".
I will put example in code below.
Can i do something like $usernames = array("username#domain1.com", $X) where $X = <anything-so-long-as-not-blank>#domain3.com?
Full Code Below:
<?php
//VALIDATE USERS
$usernames = array("username#domain1.com", "username2#domain1.com", "username3#domain1.com", "username1#domain2.com", "username2#domain2.com", "username1#domain3.com");
$passwords = array("password1", "password2", "password3", "password4", "password5", "password6");
//REDIRECT SPECIFIC VALID USERS OR DOMAIN
function get_page($username) {
$username = strtolower($username);
switch ($username) {
case "username#domain1.com" : return "http://www.google.com";
case "username2#domain1.com" : return "http://www.yahoo.com";
case "username3#domain1.com" : return "http://www.stackoverflow.com";
case "username1#domain2.com" : return "http://www.serverfault.com";
}
return preg_match('/#domain3\.com$/',$username) ?
"http://www.backblaze.com" : "DefaultBackupPage.php";
}
$page = get_page($_POST['username']);
for($i=0;$i<count($usernames);$i++)
{
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++)
{
if ($usernames[$i] == $_POST["username"])
{
$found = 1;
}
}
if ($found == 0)
{
header('Location: login.php?login_error=1');
exit;
}
if($logindata[$_POST["username"]]==$_POST["password"])
{
session_start();
$_SESSION["username"]=$_POST["username"];
header('Location: '.$page);
exit;
}
else
{
header('Location: login.php?login_error=1');
exit;
}
?>
#inhan Has already helped me like a champ. I am wondering if any one can get me over the line? Cheers!
Your code needed a clean-up first. There's a bunch of errors in it if you do a test run. It's also a bit hard to read IMO.
I've attached a working code sample below.
// Get users
$input_pwd = ( isset( $_POST["password"] ) ? $_POST["password"] : '' );
$input_user = ( isset( $_POST["username"] ) ? $_POST["username"] : '' );
// Your pseudo database here ;)
$usernames = array(
"username#domain1.com",
"username2#domain1.com",
"username3#domain1.com",
"username1#domain2.com",
"/[a-z][A-Z][0-9]#domain2\.com/", // use an emtpy password string for each of these
"/[^#]+#domain3\.com/" // entries if they don't need to authenticate
);
$passwords = array( "password1", "password2", "password3", "password4", "", "" );
// Create an array of username literals or patterns and corresponding redirection targets
$targets = array(
"username#domain1.com" => "http://www.google.com",
"username2#domain1.com" => "http://www.yahoo.com",
"username3#domain1.com" => "http://www.stackoverflow.com",
"username1#domain2.com" => "http://www.serverfault.com",
"/[a-z][A-Z][0-9]#domain2\.com/" => "http://target-for-aA1-usertypes.com",
"/[^#]+#domain3\.com/" => "http://target-for-all-domain3-users.com",
"/.+/" => "http://default-target-if-all-else-fails.com",
);
$logindata = array_combine( $usernames, $passwords );
if ( get_user_data( $input_user, $logindata ) === $input_pwd ) {
session_start();
$_SESSION["username"] = $input_user;
header('Location: ' . get_user_data( $input_user, $targets ) );
exit;
} else {
// Supplied username is invalid, or the corresponding password doesn't match
header('Location: login.php?login_error=1');
exit;
}
function get_user_data ( $user, array $data ) {
$retrieved = null;
foreach ( $data as $user_pattern => $value ) {
if (
( $user_pattern[0] == '/' and preg_match( $user_pattern, $user ) )
or ( $user_pattern[0] != '/' and $user_pattern === $user)
) {
$retrieved = $value;
break;
}
}
return $retrieved;
}

delete uploaded file from an array of id when they are delted in joomla?

I am trying to delete an array of ids and when it gets deleted I want the uploaded pic associated with it also to get deleted using unlink. I am using joomla and mysql for the admin mvc component in joomla.
My code for controller in remove is has follows:
function remove()
{
$arrayIDs = JRequest::getVar ( 'cid', null, 'default', 'array' );
//Reads cid as an array
$model = & $this->getModel ( 'greetings' );
jimport ( 'joomla.filesystem.file' );
if (is_array ( $arrayIDs ) && count ( $arrayIDs ) > 0) {
foreach ( $arrayIDs as $k => $id ) {
$del = $model->deleteGreetings ( $arrayIDs );
if ($del) {
$getdeleted = $model->getUploadpic ( $id );
$deletefile = JPATH_COMPONENT . DS . "uploads" . DS . $uploadedfile;
unlink ( $deletefile );
}
}
}
if ($arrayIDs === null) { //Make sure the cid parameter was in the request
JError::raiseError ( 500, 'cid parameter missing from the request' );
}
$redirectTo = JRoute::_ ( 'index.php?option=' . JRequest::getVar ( 'option' ) );
$this->setRedirect ( $redirectTo, 'Deleted...' );
}
...and for the model my code is:
function deleteGreetings($arrayIDs) {
$query = "DELETE FROM #__greetings WHERE id IN (" . implode ( ',', $arrayIDs ) . ")";
$db = $this->getDBO ();
$db->setQuery ( $query );
if (! $db->query ()) {
$errorMessage = $this->getDBO ()->getErrorMsg ();
JError::raiseError ( 500, 'Error deleting greetings: ' . $errorMessage );
} else {
return TRUE;
}
}
You have a few problems in your code:
$uploadedfile is never declared but it is used to find the file path. I assume this is the same as $getdeleted.
You have a foreach loop around the elements in your array which will pick up each element in turn. However you model function deleteGreetings takes the entire array. Your should remove this function call from your loop else it will be called each for every element in the array. You only want to call this once.
Only at the end of your controller do you check if your cid param is null ... what is the point? You should check this first before trying to run any of the other code.
I would do something like this:
$arrayIDs = JRequest::getVar ( 'cid', null, 'default', 'array' );
if ($arrayIDs === null) { //Make sure the cid parameter was in the request
JError::raiseError ( 500, 'cid parameter missing from the request' );
}
$model = & $this->getModel ( 'greetings' );
jimport ( 'joomla.filesystem.file' );
if (is_array ( $arrayIDs ) && count ( $arrayIDs ) > 0) {
$del = $model->deleteGreetings ( $arrayIDs );
// check this outside the loop, if it is inside you are checking it for
// each element in the array. Here we check once and then go forward.
if ($del) {
foreach ( $arrayIDs as $k => $id ) {
$uploadedfile = $model->getUploadpic ( $id );
$deletefile = JPATH_COMPONENT . DS . "uploads" . DS . $uploadedfile;
JFile::delete($deletefile);
//unlink ( $deletefile );
}
}
}

Categories