PHP object can not access variable - php

Using the following:
$last_book = tz_books::getLast($request->db, "WHERE book_id='{$request->book_id}'");
I get the following php object array,
[0] => tz_books Object
(
[db:tz_books:private] => com Object
[id] => 64BEC207-CA35-4BD2
[author_id] => 4F4755B4-0CE8-4251
[book_id] => 8FC22AA0-4A60-4BFC
[date_due] => variant Object
)
I then want to use the author_id, but for some reason it's not working.
Trying to use:
$tz_books->author_id;
Using print_r($last_book); prints the array to the console just fine. And Doing the following just to see if the correct variable was being used:
$author = $tz_books->author_id;
print_r($author);
Nothing is printed to the console, and even after digging through the php manual and trying a lot of alternatives, I can't seem to grab that variable. I'm hoping i'm making a rookie mistake and overlooking something stupid. Thank you for any help!
Edit: Class definition
private $db;
public $id;
public $author_id;
public $book_id;
public $date_due;
public function __construct($db, $values=null) {
$this->db = $db;
if ( $values != null ) {
foreach ( $values as $var => $value ) {
$this->$var = $value;
}
}
}
public static function retrieveAll($db, $where='', $order_by='') {
$result_list = array();
$query = 'SELECT '.
'id, '.
'author_id, '.
'book_id, '.
'date_due '.
"FROM tz_books $where $order_by";
$rs = $db->Execute($query);
while ( !$rs->EOF ) {
$result_list[] = new tz_books($db, array(
'id' => clean_id($rs->Fields['id']->Value),
'author_id' => clean_id($rs->Fields['author_id']->Value),
'book_id' => clean_id($rs->Fields['book_id']->Value),
'date_due' => $rs->Fields['date_due']->Value,
));
$rs->MoveNext();
}
$rs->Close();
return $result_list;
}

Your result object seems to be an array of books with 1 element.
Try
echo $tz_books[0]->author_id;
BTW, it also looks like you're escaping input by putting single quotes. This is not a reliable/recommended method. Use a database-specific escape function like this

Related

Why getPostParameters doesn't work on symfony 1.4?

I have a form in symfony 1.4 which are created for each competence. My forms was created with success. But when I try to save my form I can't. I go to see my action code and the function getPostParameters seem dosn't work. I use getParameterHolder to see what's wrong in my parameters but after I put the good value the getPostParameters function doesn't work.
This is what I get from getParameterHolder:
sfParameterHolder Object
([parameters:protected] => Array
(
[professionnal_competence] => Array
(
[rayon_competence3] => 24
[rayon_competence9] => 22
[rayon_competence19] => 32
)
[module] => professionnal_subregion
[action] => saveCompetenceRadius
)
)
And my function:
public function executeSaveCompetenceRadius(sfWebRequest $request) {
$user = $this->getUser()->getGuardUser();
$q = ProfessionnalCompetenceQuery::create()
->addSelect('pc.*')
->where('pc.professionnal_id= ?', $user->getId());
$res = $q->execute();
$values = $request->getPostParameters(['professionnal_competence']);
$test = $request->getParameterHolder();
var_dump($values); print_r($values); print_r($request->getParameterHolder());
exit;
foreach ($res as $professionnalCompetence) {
foreach ($values['professionnal_competence'] as $k => $val) {
if ($k == 'rayon_competence' . $professionnalCompetence->getCompetenceId()) {
$professionnalCompetence->setRayonCompetence($val);
$professionnalCompetence->save();
}
}
}
return $this->renderComponent('professionnal_subregion', 'competenceRadius');
// return "test";
//return $this->renderPartial('professionnal_subregion/competenceradius');
}
This is my form:
class ProfessionnalCompetenceRadiusForm extends BaseProfessionnalCompetenceForm {
public function configure()
{
unset($this['rayon_competence']);
$this->widgetSchema['rayon_competence'.$this->object->getCompetenceId()] = new sfWidgetFormSelectUISlider(array('max'=>50,'step'=>1));
$this->widgetSchema->setHelp('rayon_competence'.$this->object->getCompetenceId(),'en kilomètres');
$this->widgetSchema->setLabel('rayon_competence'.$this->object->getCompetenceId(),'rayon');
$this->setValidator('rayon_competence'.$this->object->getCompetenceId(), new sfValidatorInteger(array('max'=>50)));
}
}
Someone has an idea or can help me ?? Because I try lot of thing but without success. Thank in advance :).
I think the error hides in this line:
$values = $request->getPostParameters(['professionnal_competence']);
You're passing an array to a function that takes a string. Try removing the brackets around 'professionnal_competence'.
EDIT: Scratch that. getPostParameters takes no parameters. getPostParameter, on the other hand, takes two - the first of which is the field name - a string. So, your code should be:
$values = $request->getPostParameter('professionnal_competence');
The error is here:
$values = $request->getPostParameters(['professionnal_competence']);
The function sfWebRequest::getPostParameters doesn't actually take parameters.
You can either access this array with [...], or use getPostParameter, which allows "safe" deep access:
$val = $request->getPostParameter('a[b]');
// basically the same as, but with error checks:
$val = $request->getPostParameters()['a']['b'];

Laravel 5 WhereIn Not Working

I have no idea why my query is suddenly not working (although maybe it was never working to begin with). Is there anything wrong here?
My controller;
$dataset = $postcode_lookup->dataset; // will return "201502_postcode"
$postcode_extract = new PostcodeExtract;
$postcode_extract = $postcode_extract->setTableByDate($dataset);
foreach ($input as $column => $values) {
$postcode_extract->orWhere(function ($query) use ($column, $values) {
$query->whereIn($column, $values);
});
}
/*
* Temporarily print out the raw SQL...
*/
$sql = str_replace(['%', '?'], ['%%', "'%s'"], $postcode_extract->toSql());
$fullSql = vsprintf($sql, $postcode_extract->getBindings());
print_r($fullSql);
exit;
My model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
public function setTableByDate($selected_tablename)
{
$this->table = $selected_tablename;
// Return $this for method chaining
return $this;
}
public function getTable()
{
if (isset($this->table))
$this->setTableByDate($this->table);
return $this->table;
}
All that the print out of the raw sql is returning is select * from 201502_postcode and is just ignoring the rest of the query.
This is my $input array;
Array
(
[country] => Array
(
[0] => L93000001
[1] => M83000003
)
[county] => Array
(
[0] => 95
)
)
orWhere and whereIn is just being ignored it seems..
--- UPDATE ---
I didn't know about orWhereIn. But having tried this;
foreach ($input as $column => $values) {
$postcode_extract->orWhereIn($column, $values);
print "<br>";
print $column;
print "<br>";
print_r($values);
print "<br>";
}
I still get the same result. It's like this loop is being totally ignored - even though I can get these print's/print_r's to work. The raw SQL is still just select * from 201502_postcode.
Try this
$postcode_extract->orWhereIn($column, $values)
Also, if that doesnt work, try making the first one condition a whereIn and the rest a orWhereIn
Oh this is so frustratingly obvious I think I might cry...
foreach ($input as $column => $values) {
$postcode_extract = $postcode_extract->orWhereIn($column, $values);
}

Print array into another array [Zend]

I use Zend 1
CONTROLLER:
public function insertarAction() {
$entidades_salud = new Application_Model_DbTable_EntidadesSalud();
$datos_entidades = $entidades_salud->buscarEntidades();
}
MODEL:
<?php
class Application_Model_DbTable_EntidadesSalud extends Zend_Db_Table_Abstract
{
protected $_name = 'entidades_salud';
protected $_primary = 'codigo_entidad_salud';
public function buscarEntidades() {
$consulta = $this->select()->from($this->_name);
$query = $this->fetchAll($consulta)->toArray();
return $query;
}
}
PRINT OF CONSULT [print_r($datos_entidades); - in controller]
Array ( [0] => Array ( [codigo_entidad_salud] => 1 [nombre_entidad] => SANITAS )
[1] => Array ( [codigo_entidad_salud] => 3 [nombre_entidad] => wladfimir )
[2] => Array ( [codigo_entidad_salud] => 4 [nombre_entidad] => Juli ))
no entraArray ( [controller] => beneficiarios [action] => insertar [module] => default )
According to the above result, I require print:
1 SANITAS
3 wladfimir
4 Juli
I think it should work with something like:
while($row = mysqli_fetch_assoc($datos_entidades)){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
What you need is foreach loop to iterate through an array.
foreach($datos_entidades as $row){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
Note: The display logic should fall into the view file, you should pass data to view & in view file you need loop to display the records.
You are converting The results into array,
you can do what Rikesh Suggested as,
foreach($datos_entidades as $row){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
And you can pass $datos_entidades to View Script
as $this->view->data= $datos_entidades;
and you will be able to use,
foreach($this->data as $row){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
in your view script also,
an alternate approach,
You dont use toArray() in $query = $this->fetchAll($consulta)->toArray();
just use, $query = $this->fetchAll($consulta);
and you will be able access it like following,
foreach($datos_entidades as $row){
echo $row->codigo_entidad_salud;
echo $row->nombre_entidad;
}
and will be able to access same way in view script also.

Accessing WP cron multidimensional array efficiently in PHP

I need to access multiple arrays, the problem lies when I get to the arrays I need like below, I can't access it traditionally because the key will be different every time.
I'm dealing with the following array:
Array
(
[oe_schedule_charge] => Array
(
[617cdb2797153d6fbb03536d429a525b] => Array
(
[schedule] =>
[args] => Array
(
[0] => Array
(
[id] => cus_2OPctP95LW8smv
[amount] => 12
)
)
)
)
)
There are going to be hundreds of these arrays and I need a way to efficiently access the data within them. I'm using the following code with expected output:
function printValuesByKey($array, $key) {
if (!is_array($array)) return;
if (isset($array[$key]))
echo $key .': '. $array[$key] .'<br>';
else
foreach ($array as $v)
printValuesByKey($v, $key);
}
$cron = _get_cron_array();
foreach( $cron as $time => $hook ) {
if (array_key_exists('oe_schedule_charge', $hook)) {
echo '<div>';
echo date('D F d Y', $time);
echo printValuesByKey($hook, 'amount');
echo printValuesByKey($hook, 'id');
echo '</div>';
}
}
But I've never had to deal with this much data, so I would like to take the proper precautions. Any light that can be shed on accessing a multidimensional array like this in an efficient way would be greatly appreciated.
I would consider loading it into an object, then writing member functions to get what you want.
class myclass {
private $_uniqueKey;
private $_schedule;
private $_args = array();
private $_amount = array();
private $_id = array();
public function __construct($arrayThing)
{
foreach($arrayThing['oe_schedule_charge'] as $uniqueKey => $dataArray)
{
$this->_uniqueKey = $uniqueKey;
$this->_schedule = $dataArray['schedule'];
$this->_args = $dataArray['args'];
}
$this->_afterConstruct();
}
private function _afterConstruct()
{
foreach($this->_args as $argItem)
{
if(isset($argItem['amount']) && isset($argItem['id']))
{
$this->_amount[] = $argItem['amount'];
$this->_id[] = $argItem['id'];
}
}
}
public function getUniqueKey()
{
return $this->_uniqueKey;
}
public function getSchedule()
{
return $this->_schedule;
}
public function getArgs()
{
return $this->_args;
}
public function printShitOut($time)
{
//You define this. But if you do a print_r( on the object, it will tell you all the items you need. )
}
//code would be like this:
$cron = _get_cron_array();
foreach( $cron as $time => $hook )
{
$obj = new myclass($hook);
$obj->printShitOut($time);
}

PHP Variable Variables

I am writing this comment class:
class Comment {
public $id;
public $post_id;
public $name;
public $email;
public $website;
public $body;
public $date;
public $ip_address;
public $status;
function __construct($id) {
global $db;
$resc = $db->query("SELECT * FROM blog_comments WHERE id='$id' LIMIT 1");
while($row = $db->fetch_assoc($resc)) {
while ($comment = current($row)) {
$key = key($row);
$this->$key = $comment{$key};
next($row);
}
}
}
}
Here is what the query inside the constructor will return when run in the database:
query results http://17webshop.com/wp-content/uploads/2009/10/Picture-2.png
But when I run it, this is what print_r(new Comment(1)); spits out:
Comment Object
(
[id] => 1
[post_id] => 1
[name] => J
[email] => j
[website] => h
[body] => b
[date] => 1
[ip_address] => :
[status] => 1
)
Any ideas why I'm only getting the first character of each field?
Thanks.
You want
$comment[$key]
$comment{$key} will give you the nth character of a string. Since $key itself is a string, PHP converts that to an integer 0 and you get the first char.
current/next is painful, and I'm not sure what's with the {} dereferencing.
Why not just:
$resc = $db->query("SELECT * FROM blog_comments WHERE id='$id' LIMIT 1");
while($row = $db->fetch_assoc($resc)) {
foreach($row as $key=>$value){
$this->$key = $value;
}
}
I think you need to change this line:
$this->$key = $comment{$key};
with:
$this->$key = $comment[$key];

Categories