I want to load the data from a JSON file into a table. (With Zend Framework)
This is my JSON file markup:
{
"wijken": {
"11": {
"coords": "3.79073170001967,51.1717753664505,0 3.79020920176376,51.1723018883706,0 3.78989543642226,51.1729670713336,0 3.78983091856725,51.1736482209016,0 3.79035112720225,51.174896701853",
"id": "kml_1",
"fid": "0",
"wijziging": "Ja",
"nieuwnr": "11",
"naam": "Noordoost",
"wijk": "Kanaaldorpen en -zone",
"wijknr": "11",
"objectid": "1",
"area": "0",
"len": "0"
}
}
I know how to do this with clear php: (and it works)
<?php
//connection to database
$$connect = mysql_connect('localhost', 'root', 'root');
$db = mysql_select_db('testdatabase');
// ALLE VELDEN LEEGMAKEN
mysql_query("TRUNCATE TABLE wijken");
// url from json file
$url = "http://data.appsforghent.be/poi/wijken.json";
//get content from json file
$json = file_get_contents($url);
// OM ALLES VAN IN DE JSON FILE TE TONENE
//var_dump(json_decode($json));
//var_dump(json_decode($json, true));
$out = json_decode($json, true);
foreach($out["wijken"] as $wijk)
{
// ID + NAAM + WIJK + WIJKNR + COORDINATEN
$coords = addslashes($wijk[coords]);
$id = addslashes($wijk[id]);
$fid = addslashes($wijk[fid]);
$wijziging = addslashes($wijk[wijziging]);
$nieuwnr = addslashes($wijk[nieuwnr]);
$naam = addslashes($wijk[naam]);
$wijk = addslashes($wijk[wijk]);
$wijknr = addslashes($wijk[wijknr]);
$objectid = addslashes($wijk[objectid]);
$area = addslashes($wijk[area]);
$len = addslashes($wijk[len]);
mysql_query("INSERT INTO wijken (coords, id, fid, wijziging, nieuwnr, naam, wijk, wijknr, objectid, area, len)
VALUES('$coords', '$id', '$fid', '$wijziging', '$nieuwnr', '$naam', '$wijk', '$wijknr', '$objectid', '$area', '$len')") or die (mysql_error());
}
?>
But how can I implement this in Zend Framework?
What I have till now in my models map in Zend Framework:
Map "DbTable" with Districts.php in it:
class Backoffice_Model_DbTable_Districts extends Zend_Db_Table_Abstract
{
protected $_name = 'Wijken';
}
District.php with getters and setters:
class Backoffice_Model_District extends Ahs_Model_Abstract
{
protected $coords;
protected $id;
protected $fid;
protected $wijziging;
protected $nieuwnr;
protected $naam;
protected $wijk;
protected $wijknr;
protected $objectid;
protected $area;
protected $len;
public function getCoords()
{
return $this->coords;
}
public function setCoords($coords)
{
$this->coords = $coords;
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getFid()
{
return $this->fidid;
}
public function setFid($fid)
{
$this->fid = $fid;
}
public function getWijziging()
{
return $this->wijziging;
}
public function setWijziging($wijziging)
{
$this->wijziging = $wijziging;
}
public function getNieuwnr()
{
return $this->nieuwnr;
}
public function setNieuwnr($nieuwnr)
{
$this->nieuwnr = $nieuwnr;
}
public function getNaam()
{
return $this->naam;
}
public function setNaam($naam)
{
$this->naam = $naam;
}
public function getWijk()
{
return $this->wijk;
}
public function setWijk($wijk)
{
$this->wijk = $wijk;
}
public function getObjectid()
{
return $this->objectid;
}
public function setObjectid($objectid)
{
$this->objectid = $objectid;
}
public function getArea()
{
return $this->area;
}
public function setArea($area)
{
$this->area = $area;
}
public function getLen()
{
return $this->len;
}
public function setLen($len)
{
$this->len = $len;
}
}
Now I have a DistrictMapper.php, but how can I implement the code to load everything from the json in my database?
What I have till now:
protected $_dbTable;
public function __construct()
{
$this->_dbTable = new Backoffice_Model_DbTable_Districts();
}
public function fetchAll()
{
$rowset = $this->_dbTable->fetchAll();
$districts = $this->_toObjects($rowset);
return $districts;
}
And now I need to make the save and toobject.
public function save(Backoffice_Model_Admin $admin)
{
$data = array('coords' => $district->getCoords(),
'id' => $district->getId(),
'fid' => $district->getFid(),
'wijziging' => $district->getWijziging(),
'nieuwnr' => $district->getNieuwnr(),
'naam' => $district->getNaam(),
'wijk' => $district->getWijk(),
'wijknr' => $district->getWijknr(),
'objectid' => $district->getObjectid(),
'area' => $district->getArea(),
'len' => $district->getLen(),
);
}
protected function _toObject(Zend_Db_Table_Row_Abstract $row = null)
{
}
From the Zend docs, Zend_DbTable::insert(), and adapted to your other posted table info:
public function save(Backoffice_Model_Admin $admin){
$data = array(
"fid": "0",
"wijziging": "Ja",
"nieuwnr": "11",
// other data from $admin...
);
$table = new Backoffice_Model_DbTable_Districts();
$table->insert($data);
}
Construct your array; pass it in.
Related
I created a Parent class Arbre
<?php
class Arbre
{
/*
* #var string
*/
protected string $espece;
protected int $recolteFruit;
protected string $numero;
protected int $maxFruit = 100;
protected int $minFruit = 90;
protected static $registry = array();
public function __construct($numero, $espece, $recolteFruit)
{
$this->numero = $numero;
$this->checkVars();
$this->espece = $espece;
$this->setRecolteFruit($recolteFruit, $this->maxFruit, $this->minFruit);
self::$registry[] = $this->numero;
}
public function setEspece($espece)
{
$this->espece = $espece;
}
public function setMaxFruit($maxFruit)
{
$this->maxFruit = $maxFruit;
}
public function setMinFruit($minFruit)
{
$this->minFruit = $minFruit;
}
public function setRecolteFruit($recolteFruit, $maxFruit,$minFruit )
{
if (($recolteFruit > $maxFruit) || ($recolteFruit < $minFruit)) {
throw new Exception('La récolte de fruit doit être comprise entre ' . $minFruit . ' et ' . $maxFruit);
}else{
$this->recolteFruit = $recolteFruit;
}
}
public function getEspece()
{
return $this->espece;
}
public function getMaxFruit()
{
return $this->maxFruit;
}
public function getMinFruit()
{
return $this->minFruit;
}
public function getRecolteFruit()
{
return $this->recolteFruit;
}
public function getNumero()
{
return $this->numero;
}
public function checkVars()
{
if (empty($this->numero)) {
throw new Exception('Numero is a required parameter.');
}
elseif (in_array($this->numero, self::$registry))
{
throw new Exception('ID "'.$this->numero.'" was used already. Please insert a unique name.',101);
}
}
}
And 2 kids classes :
Poirier.php
<?php
require('Tree.php');
class Poirier extends Arbre
{
public int $maxFruit = 20;
public int $minFruit = 0;
public int $recolteFruit;
public function __construct($numero, $espece, $recolteFruit)
{
parent::__construct($numero, $espece, $recolteFruit);
}
}
Pommier.php
<?php
require('Tree.php');
class Pommier extends Arbre
{
public int $maxFruit = 50;
public int $minFruit = 40;
public int $recolteFruit;
public function __construct($numero, $espece, $recolteFruit)
{
parent::__construct($numero, $espece, $recolteFruit);
}
}
In my index.php, I tried to loop my kids classes but I got an error
<?php
require('class/Pommier.php');
require('class/Poirier.php');
for ($i=1; $i <11 ; $i++) {
$monPommier = new Pommier('P'.$i,'Pommier', 45);
$monPoirier = new Poirier('A'.$i,'Poirier', 15);
echo $monPommier->getNumero()." ".$monPommier->getEspece() ." ". $monPommier->getRecolteFruit(). "\n";
echo $monPoirier->getNumero()." ".$monPoirier->getEspece() ." ". $monPoirier->getRecolteFruit(). "\n";
}
Here is the error
PHP Fatal error: Cannot declare class Arbre, because the name is already in use in E:\web_projects\Verger_POO2\class\Tree.php on line 3
But When I tried to call one at once, it's working
I want to create JSON model and API for array of JSON object.
my PHP code:
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_POST['type'])) {
$type = $_POST['type'];
$result = mysql_query("SELECT *FROM bidsproject WHERE type='$type'
ORDER BY createTime ") ;
if (mysql_num_rows($result)>0) {
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["projectId"] = $row["projectId"];
$product["title"] = $row["title"];
$product["createTime"] = $row["createTime"];
array_push($response["products"], $product);
}
echo json_encode($response);
}
else {
}
}
else {
}
?>
and my JSON model:
public class browsprojectJm {
int success;
public int getSuccess() {
return success;
}
public void setSuccess(int success) {
this.success = success;
}
DataToken project;
public class DataToken{
int projectId;
String title;
String creaeteTime;
public int getId() {
return projectId;
}
public void setId(int id) {
this.projectId = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return creaeteTime;
}
public void setDate(String date) {
this.creaeteTime=date;
}
}
}
and my API:
#FormUrlEncoded
#POST("project/searchBidProject.php")
Call<List<browsprojectJm>> browsproject(#Field("type") int
type_register);
output with postman:
{
"products": [
{
"projectId": "1",
"title": "خرید خانه",
"createTime": "2018-09-05"
},
{
"projectId": "3",
"title": "خرید خانه شخصی",
"createTime": "2018-09-05"
},
{
"projectId": "4",
"title": "خرید من",
"createTime": "2018-09-05"
}
]
}
but this not working and i don't know what's wrong. it fails without errors but I think this problem is from JSON model or api.I'm new in android developing and please explain for me clearly
Hello why I have this execption:
This is controller:
public function addnew(Request $request)
{
$data = \Input::except(array('_token')) ;
$rule=array(
'restaurant_type' => 'required',
'restaurant_name' => 'required',
'restaurant_address' => 'required',
'restaurant_logo' => 'mimes:jpg,jpeg,gif,png'
);
$validator = \Validator::make($data,$rule);
if ($validator->fails())
{
return redirect()->back()->withErrors($validator->messages());
}
$inputs = $request->all();
if(!empty($inputs['id'])){
$restaurant_obj = Restaurants::findOrFail($inputs['id']);
}else{
$restaurant_obj = new Restaurants;
}
//Slug
if($inputs['restaurant_slug']=="")
{
$restaurant_slug = str_slug($inputs['restaurant_name'], "-");
}
else
{
$restaurant_slug =str_slug($inputs['restaurant_slug'], "-");
}
//Logo image
$restaurant_logo = $request->file('restaurant_logo');
if($restaurant_logo){
\File::delete(public_path() .'/upload/restaurants/'.$restaurant_obj->restaurant_logo.'-b.jpg');
\File::delete(public_path() .'/upload/restaurants/'.$restaurant_obj->restaurant_logo.'-s.jpg');
$tmpFilePath = 'upload/restaurants/';
$hardPath = substr($restaurant_slug,0,100).'_'.time();
$img = Image::make($restaurant_logo);
$img->fit(120, 120)->save($tmpFilePath.$hardPath.'-b.jpg');
$img->fit(98, 98)->save($tmpFilePath.$hardPath. '-s.jpg');
$restaurant_obj->restaurant_logo = $hardPath;
}
$user_id=Auth::User()->id;
$restaurant_obj->user_id = $user_id;
$restaurant_obj->restaurant_type = $inputs['restaurant_type'];
$restaurant_obj->restaurant_name = $inputs['restaurant_name'];
$restaurant_obj->restaurant_slug = $restaurant_slug;
$address = $restaurant_obj->restaurant_address = $inputs['restaurant_address'];
$restaurant_obj->restaurant_description = $inputs['restaurant_description'];
//ne radi??
$getGeoCode = Geocode::make()->address($address);
if($getGeoCode){
$latitude = $getGeoCode->latitude();
$longitude = $getGeoCode->longitude();
$restaurant_obj->latitude = $inputs['latitude'];
$restaurant_obj->longitude = $inputs['longitude'];
}
$restaurant_obj->open_monday = $inputs['open_monday'];
$restaurant_obj->open_tuesday = $inputs['open_tuesday'];
$restaurant_obj->open_wednesday = $inputs['open_wednesday'];
$restaurant_obj->open_thursday = $inputs['open_thursday'];
$restaurant_obj->open_friday = $inputs['open_friday'];
$restaurant_obj->open_saturday = $inputs['open_saturday'];
$restaurant_obj->open_sunday = $inputs['open_sunday'];
$restaurant_obj->save();
if(!empty($inputs['id'])){
\Session::flash('flash_message', 'Changes Saved');
return \Redirect::back();
}else{
\Session::flash('flash_message', 'Added');
return \Redirect::back();
}
}
This is model:
class Restaurants extends Model
{
protected $table = 'restaurants';
protected $fillable = ['type', 'restaurant_name','restaurant_slug','restaurant_description','restaurant_address','delivery_charge','restaurant_logo', 'latitude', 'longitude'];
public $timestamps = false;
public function restaurants()
{
return $this->hasMany('App\Restaurants', 'id');
}
public static function getRestaurantsInfo($id)
{
return Restaurants::find($id);
}
public static function getUserRestaurant($id)
{
return Restaurants::where('user_id',$id)->count();
}
public static function getMenuCategories($id)
{
return Categories::where('restaurant_id',$id)->count();
}
public static function getMenuItems($id)
{
return Menu::where('restaurant_id',$id)->count();
}
public static function getOrders($id)
{
return Order::where('restaurant_id',$id)->count();
}
public static function getTotalRestaurants()
{
return Restaurants::count();
}
public function scopeSearchByKeyword($query, $keyword)
{
if ($keyword!='') {
$query->where(function ($query) use ($keyword) {
$query->where("restaurant_address", "LIKE","%$keyword%")
->orWhere("restaurant_name", "LIKE", "%$keyword%");
});
}
return $query;
}
public static function getRestaurantOwnerInfo()
{
$rest=Restaurants::find($id);
return User::find($rest->user_id);
}
}
I try everything that can remember composer dump-autoload, php artisan migrate:rollback, and again make migration etc. I have fields in my db latitude and longitude. Thanks.
It seems you're wanting to do the following by the code you posted:
if($getGeoCode){
$restaurant_obj->latitude = $getGeoCode->latitude();
$restaurant_obj->longitude = $getGeoCode->longitude();
}
$inputs['latitude'] doesnt existe . add latidue into your rule validation to make sur or do dd(Input:all()) to make sure $inputs['latitude'] exist
I've made a website in symfony. This website contains some forms with a checkbox choice and other fields.
The datas from the checkbox are serialized on flush.
It's all good.
Now i have to export this datas and i use the data exporter library from Sonata project. But the datas are still serialized and i have some things like that in my csv file:
a:2:{i:0;s:6:"Volets";i:1;s:22:"Panneau de remplissage";}
How can I unserialize my datas in order to have a clean csv file?
Here's my code
My controller
/**
* #Security("has_role('ROLE_WEBFORM')")
*/
public function exportAction(Request $request)
{
$filters = array();
$this->handleFilterForm($request, $filters);
if (!$filters['webform']) {
throw $this->createNotFoundException();
}
$webForm = $this->getRepository('CoreBundle:WebForm')->find($filters['webform']);
$source = new WebFormEntryIterator($webForm, $this->getEntityManager(), $this->get('ines_core.embedded_form.field_type_registry'), $filters);
return WebFormEntryExporter::createResponse('export.csv', $source);
}
and my class WebFormEntryExporter
class WebFormEntryExporter
{
public static function createResponse($filename, SourceIteratorInterface $source)
{
$writer = new CsvWriter('php://output', ';', '"', "", true, true);
$contentType = 'text/csv';
$callback = function() use ($source, $writer) {
$handler = \Exporter\Handler::create($source, $writer);
$handler->export();
};
return new StreamedResponse($callback, 200, [
'Content-Type' => $contentType,
'Content-Disposition' => sprintf('attachment; filename=%s', $filename)
]);
}
}
And my WebFormEntryIterator
class WebFormEntryIterator implements SourceIteratorInterface
{
protected $em;
protected $registry;
protected $repository;
protected $query;
protected $webForm;
protected $iterator;
public function __construct(WebForm $webForm, EntityManager $em, FieldTypeRegistry $registry, array $filters)
{
$this->webForm = $webForm;
$this->em = $em;
$this->registry = $registry;
$this->initQuery($filters);
}
/**
* {#inheritdoc}
*/
public function current()
{
$current = $this->iterator->current();
$entity = $current[0];
$data = [];
$data['ID'] = $entity->getId();
$data['Formulaire'] = $this->webForm->getName();
$data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
$header = $fieldConfig->getLabel();
$meta = $entity->getContentMeta($fieldConfig->getName());
$extension = $this->registry->get($meta->getFormat());
if (method_exists($extension, 'setEntityManager')) {
$extension->setEntityManager($this->em);
}
$value = $extension->formatMeta($meta);
$data[$header] = $value;
unset($extension);
}
$this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
unset($entity);
unset($webForm);
return $data;
}
/**
* {#inheritdoc}
*/
public function next()
{
$this->iterator->next();
}
/**
* {#inheritdoc}
*/
public function key()
{
return $this->iterator->key();
}
/**
* {#inheritdoc}
*/
public function valid()
{
return $this->iterator->valid();
}
/**
* {#inheritdoc}
*/
public function rewind()
{
if ($this->iterator) {
throw new InvalidMethodCallException('Cannot rewind a Doctrine\ORM\Query');
}
$this->iterator = $this->query->iterate();
$this->iterator->rewind();
}
protected function initQuery(array $filters)
{
$repository = $this->em->getRepository('InesCoreBundle:Content');
$qb = $repository->getWebFormEntryQueryBuilder();
$repository->applyWfeFilters($qb, $filters);
$this->query = $qb->getQuery();
}
}
Sorry for my broken English.
Thanks a lot
thanks chalasr.
I have to make the tratment in this file, in the current() function.
This is what I've done:
public function current()
{
$current = $this->iterator->current();
$entity = $current[0];
$data = [];
$data['ID'] = $entity->getId();
$data['Formulaire'] = $this->webForm->getName();
$data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
$header = $fieldConfig->getLabel();
$meta = $entity->getContentMeta($fieldConfig->getName());
$extension = $this->registry->get($meta->getFormat());
if (method_exists($extension, 'setEntityManager')) {
$extension->setEntityManager($this->em);
}
$value = $extension->formatMeta($meta);
if($this->is_serialized($value)) {
$value = unserialize($value);
$data[$header] = implode(' | ', $value);
} else {
$data[$header] = $value;
}
unset($extension);
}
$this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
unset($entity);
unset($webForm);
return $data;
}
public function is_serialized($data)
{
if (trim($data) == "") { return false; }
if (preg_match("/^(i|s|a|o|d){1}:{1}(.*)/si",$data)) { return true; }
return false;
}
I created a standart class Loadercontent(controller) in Codeigniter.
Also in the same file a add abstract Search class and child class SearchDoctor:
When I try to get CI instance &get_instance(); at abstract constructor, I get NULL:
$this->_ci =&get_instance();
var_dump($this->_ci); // NULL
So after I can not use:
$this->_ci->load->view($this->view, $this->item);
because $this->_ci is empty. What is wrong in my code ot abstract class in CI? Also maybe you can ask something about code? Is it wrong?
The full code:
<?php
abstract class Search
{
protected $fields = array('country' => 'country', 'city' => 'city');
protected $table;
protected $limit = 20;
protected $offset = 0;
protected $items;
protected $rand = false;
protected $data;
protected $view;
protected $_ci;
public function __construct($input)
{
$this->_ci =&get_instance();
$this->data = $input;
$this->getPostGet();
}
public function getPostGet(){
if(empty($this->data)){
foreach($this->data as $key => $val){
$this->_check($val, $key);
}
}
}
public function _check($val, $key){
if(in_array($val, $this->fields)){
$this->items[] = $this->getField($val, $key);
}
}
public function getField($value, $key){
return $key. ' = '.$value;
}
public function doQuery(){
if(!empty($this->items)){
$limit = $this->formatLimit();
$this->items = $this->other_model->getItemsTable($this->query, $this->table, $limit);
}
}
public function formatLimit(){
$this->offset = (isset($this->data['limit'])) ? $this->data['limit'] : $this->offset;
$this->limit = (isset($this->data['limit'])) ? $this->offset + $this->limit : $this->limit;
return array('offset' => $this->limit, 'limit' => $this->limit);
}
public function addFields($array){
$this->fields = array_merge($this->fields, $array);
}
public function getView(){
$this->_ci->load->view($this->view, $this->item);
}
public function response(){
echo json_encode($this->view); die();
}
}
class SearchDoctor extends Search
{
protected $fields = array('name' => 'DetailToUsersName');
public function __construct($type)
{
$this->table = 'users';
$this->view = 'users/doctors_list';
$this->limit = 10;
$this->rand = true;
$this->addFields($this->fields);
parent::__construct($type);
}
}
/* Init class */
class Loadercontent {
public function index(){
if(isset($_GET) || isset($_POST)){
$class = 'Search';
if(isset($_POST['type'])){
$type = $_POST['type'];
$input = $_POST;
}
if(isset($_GET['type'])){
$type = $_GET['type'];
$input = $_GET;
}
$class = $class.$type;
if (class_exists($class)) {
$obj = new $class($input);
$obj->getView();
$obj->response();
}
}
}
}
?>