there is two parameters to return Object as JSON
I try to get Posts By Id And attach to Array :
// Get Considered Posts, Training, Service, Intall
public function get_considered_posts() {
$item = new stdclass();
$item->msg = 'Empty';
$item->status = false;
$result = Array();
$post = $get_post_by_id( 156 ); // Training
if ( $post ) {
$result[] = $post ;
}
$post = $get_post_by_id( 164 ); // Service
if ( $post ) {
$result[] = $post ;
}
$post = $get_post_by_id( 161 ); // Intall
if ( $post ) {
$result[] = $post ;
}
if (count( $result ) == 0 ) {
$item->msg = 'Empty';
$item->status = false;
} else {
$item->msg = 'Success';
$item->status = true;
}
$item->result = $result;
return $item;
}
Here I want to use Only 5 Properties of Every Post :
// Get Post By Id
private function get_post_by_id( $pid ) {
$post = get_post( $pid = 0 );
if ( $post ) {
if ($post->post_status == 'publish') {
$object = new stdclass();
$object->id = $post->ID;
$object->cid = $pid;
$object->title = $post->post_title;
$object->content = $post->post_content;
$object->image = ''.wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
return $object;
}
}
return $post;
}
But it shows 500 Internal Server Error
When I check error_log it show :
[17-May-2016 14:27:54 UTC] PHP Notice: Undefined variable: get_post_by_id in /home/codypars/public_html/app/wp-webservice/helper.php on line 62
[17-May-2016 14:27:54 UTC] PHP Fatal error: Function name must be a string in /home/codypars/public_html/app/wp-webservice/helper.php on line 62
How I can fix it ?
Solved: thank you CD-jS And JustOnUnderMillions. To call own functions inside PHP class the right syntax is :
this->myFunctionName( $Param1, $Param2, $Param3, ...);
Remove the $ from the front of your function names when you're calling them.
e.g.
$post = $get_post_by_id( 164 );
Should be
$post = get_post_by_id( 164 );
Related
I am trying to access php variable from wordpress shortcode function and use into og filter.
I have tried with php superglobals, set transient also, but nothing give the needed result.
Can someone take a look and help, thanks!
That's my code:
add_shortcode('test', 'get_sheet_value_shortcode');
function get_sheet_value_shortcode() {
ob_start();
$API = get_option('google_sheet_api');
$google_spreadsheet_ID = get_option('google_sheet_id');
$LANG = get_language_shortcode();
$api_key = esc_attr( $API);
$get_cell = new WP_Http();
$cell_url = "https://sheets.googleapis.com/v4/spreadsheets/$google_spreadsheet_ID/values/$LANG!A1:Z1000/?majorDimension=ROWS&key=$api_key";
$cell_response = $get_cell -> get( $cell_url);
if ( empty( $cell_response) ) {
return;
}
$json_body = json_decode($cell_response['body'],true);
$values = $json_body['values'];
//$values = json_encode($values);
array_shift($values); // removes first column key
if (! empty($values) ) {
$count = count($values);
// this will be using for share f-nality, so we can get same quote
$quote_number = array_search($rand_values, $values);
$rand_values = $values[array_rand($values)];
$image = (! empty($rand_values[3]) ) ? $rand_values[3] : '';
$GLOBALS['ogimage'] = $image;
}
ob_get_clean();
}
add_filter( 'aioseo_facebook_tags2', 'aioseo_filter_facebook_title2', 99 );
function aioseo_filter_facebook_title2( $facebookMeta ) {
$image = $GLOBALS['ogimage'];
if ( is_page('test') ) {
$facebookMeta['og:image'] = $image;
}
return $facebookMeta;
}
as the title says, I made a PHP method to update a JSON object from MySQL using a defined key-value and new-value basically the function fetches the JSON column from the database and then looping throw each object in the array and compare it to the item and if the key-value matches the item the key-value
will be replaced with the new value. as I think the problem is in the newArray because the function inserts the same old array without any changes!
<?
public function AlterJSON($billingID,$item,$key,$newValue){
if($this->connected === true){
try{
$ColumnJ = $this->connection->prepare("SELECT `items` FROM `bills` WHERE id=:id");
$ColumnJ->bindParam(":id",$billingID);
$ColumnJ->execute();
$fetched = $ColumnJ->fetchColumn();
$decoded = json_decode($fetched);
foreach($decoded as $product){
if($product->$key == $item){
$product->$key = $newValue;
$newArray = json_encode($decoded);
$alterSQL = $this->connection->prepare('UPDATE `bills` SET items=:newArray WHERE id=:id');
$alterSQL->bindParam(':newArray',$newArray);
$alterSQL->bindParam(':id',$billingID);
$alterSQL->execute();
}
}
}
catch(PDOException $e){
if($this->errors === true){
return $this->error($e->getMessage());
}else{
return false;
}
}
}
}
?>
method call($productqty and $productPrice are the key-value getting from json)
<?php
require("Core.php");
// Calling DbConnect Object //
$dbConnection = new dbConnect('127.0.0.1','root','0928065698ko','project-db');
// Billing $_PSOT //
$ProductQty = $_POST['qty-input'];
$ProductPrice = $_POST['price-input'];
$BillingTotal = $_POST['total-input'];
$BillID = $_POST['Billid'];
// Billing Requset //
if(isset($ProductPrice) && isset($ProductQty) && isset($BillingTotal)){
$dbConnection->AlterJSON($BillID,$ProductPrice,'price',$ProductPrice);
}
?>
I can't be sure if the following is correct as I have no way currently to test the JSON datatype within mysql nor a suitable table with json data so it might be riddled with mistooks.
<?php
/*
It is better to test that these POST variables are set than try to assign
as variables later not knowing if they are or are not set. `isset` will
accept multiple arguments.
*/
if( isset(
$_POST['qty-input'],
$_POST['price-input'],
$_POST['total-input'],
$_POST['Billid']
) ){
# no need to include this if the variables are not set
require('Core.php');
$dbConnection = new dbConnect('127.0.0.1','root','0928065698ko','project-db');
$ProductQty = $_POST['qty-input']; # this does not get used
$ProductPrice = $_POST['price-input'];
$BillingTotal = $_POST['total-input']; # this does not get used
$BillID = $_POST['Billid'];
$dbConnection->AlterJSON( $BillID, $ProductPrice, 'price', $ProductPrice );
}
?>
<?php
/* previous methods */
public function AlterJSON( $bid=false, $item=false, $key=false, $value=false ){
try{
if( $bid && $item && $key && $value && $this->connected === true ){
$stmt=$this->connection->prepare('select `items` from `bills` where `id`=:id');
$stmt->execute( [ ':id' => $bid ] );
$fetched = $stmt->fetchColumn();
$decoded = json_decode( $fetched );
$stmt=$this->connection->prepare('update `bills` set `items`=:json where id=:id');
foreach( $decoded as $index => $product ){
if( $product->$key == $item ){
$decoded[ $index ]->$key = $value;
$json = json_encode( $decoded );
$stmt->execute([
':json' => $json,
':id' => $bid
]);
}
}
return true;
}
return false;
} catch( PDOException $e ){
return $this->errors === true ? $this->error( $e->getMessage() ) : false;
}
}
/* more methods */
?>
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
I am trying to connect to Last.fm api through php, using the packages downloaded from https://github.com/matto1990/PHP-Last.fm-API .
Here is my code:
public function getTopArtists($methodVars) {
// Check for required variables
if ( !empty($methodVars['user']) ) {
$vars = array(
'method' => 'user.gettopartists',
'api_key' => $this->auth->apiKey
);
$vars = array_merge($vars, $methodVars);
if ( $call = $this->apiGetCall($vars) ) {
if ( count($call->topartists->artist) > 0 ) {
$i = 0;
foreach ( $call->topartists->artist as $artist ) {
$topartists[$i]['name'] = (string) $artist->name;
$topartists[$i]['rank'] = (string) $artist['rank'];
$topartists[$i]['playcount'] = (string) $artist->playcount;
$topartists[$i]['mbid'] = (string) $artist->mbid;
$topartists[$i]['url'] = (string) $artist->url;
$topartists[$i]['streamable'] = (string) $artist->streamable;
$topartists[$i]['images']['small'] = (string) $artist->image[0];
$topartists[$i]['images']['medium'] = (string) $artist->image[1];
$topartists[$i]['images']['large'] = (string) $artist->image[2];
$i++;
}
return $topartists;
}
else {
$this->handleError(90, 'This user has no top artists');
return FALSE;
}
}
else {
return FALSE;
}
}
else {
// Give a 91 error if incorrect variables are used
$this->handleError(91, 'You must include artist variable in the call for this method');
return FALSE;
}
}
But as I try to execute the same, I get a message:
Error 99 - No connection could be made because the target machine actively refused it.
i wrote this below code for my groups in my site..
public function set_group_id($group_id)
{
$db2 = & $this->network->db2;
/* if( $this->id ) {
return FALSE;
} */
if( ! $group_id ) {
return FALSE;
}
if( ! $g = $this->network->get_group_by_id($group_id) ) {
return FALSE;
}
if( !$g->is_public && $this->user->id>0 && !$this->user->is_network_admin ) {
$users = $this->network->get_group_invited_members($g->id);
if( !$users || !in_array(intval($this->user->id),$users) ) {
return FALSE;
}
}
$D->i_am_network_admin = ( $this->user->is_logged && $this->user->info->is_network_admin > 0 );
$D->i_am_admin = $D->i_am_network_admin;
if( !$D->i_am_network_admin ) {
$D->i_am_admin = $db->fetch('SELECT id FROM groups_admins WHERE group_id="'.$g->id.'" AND user_id="'.$this->user->id.'" LIMIT 1') ? TRUE : FALSE;
}
if( $g->mojaz && !$this->user->i_am_admin ) {
return FALSE;
}
$this->group = $g;
$this->to_user = FALSE;
return TRUE;
}
my error in this line ...
$D->i_am_admin = $db->fetch('SELECT id FROM groups_admins WHERE group_id="'.$g->id.'" AND user_id="'.$this->user->id.'" LIMIT 1') ? TRUE : FALSE;
i want create limiter for website groups if user is admin of site he can send a post
or if user is admin of group can send post else return false.
In your error line $db is null, because $db hadn't been declared in your function set_group_id(). I see only database object $db2
$db2 =& $this->network->db2
Try to replase $db to $db2. If $db2 contains correct database object and a handle to an open connection it will works