How to use variable name to create new variables in PHP? - php

I'm using Joomla Framework to create component that displays options from a MySQL table.
Because each option has a lot of various parameters they are being set as json arrays in custparams field.
This function extracts these custom parameters from each option based on option id.
JSON data is decoded and written into stdObject:
$_oparams=null;
function _custParamsOpt($pid)
{
$query='SELECT custparams FROM #__mycomponent_options'
.' WHERE id = '.(int)$pid;
$this->_db->setQuery( $query);
$paramdata=$this->_db->loadResult();
if (!empty($paramdata))
{
$custom=json_decode($paramdata);
foreach ($custom as $custom_params)
{
if ($custom_params->pkey=='elemvert') $this->_oparams->elemvert=$custom_params->pvalue;
if ($custom_params->pkey=='elemhor') $this->_oparams->elemhor=$custom_params->pvalue;
if ($custom_params->pkey=='minwidth') $this->_oparams->minwidth=$custom_params->pvalue;
if ($custom_params->pkey=='maxwidth') $this->_oparams->maxwidth=$custom_params->pvalue;
if ($custom_params->pkey=='minheight') $this->_oparams->minheight=$custom_params->pvalue;
if ($custom_params->pkey=='maxheight') $this->_oparams->maxheight=$custom_params->pvalue;
}
return true;
} else {
return false;
}
}
Is it possible to write this data as:
$this->_oparams->$pkey=$custom_params->pvalue;
so I can avoid listing all the parameters?
In the code later I check parameters in this way:
if (!empty($this->_oparams->maxheight)) $htmlout.="\t\t\t\t<input type=\"hidden\" name=\"maxheight".$rowx->id."\" id=\"maxheight".$rowx->id."\" value=\"".$this->_oparams->maxheight."\" />";

I believe this is what you are looking for:
...
foreach ($custom as $custom_params)
$this->_oparams->{$custom_params->pkey} = $custom_params->pvalue;
}
...

Related

Icontact api - get all contacts from list

I am using the icontact php api. I want to get the last contact who entered the list so in the icontact api php I have this:
<php
public function getContacts() {
// Make the call and return the data
return $this->makeCall("/a/{$this->setAccountId()} /c/{$this->setClientFolderId()}/contacts?listId=49626&status=total&createDate=2015-02-16&createDateSearchType=gt", 'GET');
}
?>
than I use this to call it:
<?php
$oiContact = iContactApi::getInstance();
try {
var_dump($oiContact->getContacts());
} catch (Exception $oException) { // Catch any exceptions
var_dump($oiContact->getErrors());
}
$obj = $oiContact->getLastResponse();
$data = json_decode($obj,TRUE);
echo $data['contacts'][0]['email'];
echo $data['contacts'][0]['commitmentscore'];
echo $data['contacts'][0]['firstName'];
echo $data['contacts'][0]['phone'];
?>
It keeps giving me the same contact it is because the 0 in the echo but how can I make that a variable or an if condition just not sure how
paste bins with full code
http://pastebin.com/SBf73UNb //call
http://pastebin.com/CuGcCvU1 //api
This worked
/contacts?listId=49626&orderby=createDate:desc&limit=1", 'GET');
Got it from this page
http://www.icontact.com/developerportal/documentation/advanced-users/
I think you can use orderby option,
check this link
sample they used
Get all contacts on a list ordered by First Name GET https://app.sandbox.icontact.com/icp/a/<accountId>/c/<clientFolderId>/contacts?orderby=firstName
Instead of firstname you can use date, something like normal SQL query doing then fetch only first contact.
Also the return data will be always array so you have to run within a foreach for iterate the data.
Hope it helps.

Always get an empty array in foreach loop

There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);

Store a user-input date string as datetime

I'm using php, and need to parse a date string formatted as dd/mm/yyyy and store it in MySql.
How can I convert the string to a datetime variable in a MySql table?
Probably the best way would be using this: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'
Or equivalent PHP functions like:
http://www.php.net/manual/en/function.date-parse-from-format.php (from PHP 5.3)
A generic PHP function would look like
function convertDate($dateString) {
return date('Y-m-d H:i:s',strtotime(str_replace('/','-',$dateString)));
}
or
function convertDate($dateString) {
$a = explode($dateString('/'));
return "{$a[2]}-{$a[1]}-{$a[0]} 00:00:00";
}
First of all you should store a configuration for the required format date, maybe something like this:
Knowing that the ISO_DATE FORMAT is "Y-m-d"
You must save the output configuration somehow, at least the separator.
If you know the separator and you know the format into which the date is entered than you can validate it using checkdate(), and also transform it into the ISO standard by exploding the values by the predefined separator.
I have a validation object that tells me if a field is of a certain type (String,Date,Datetime,Integer,Float) then formats the parameters sent to SQL :
as an example, let's say i get this array from my html form into PHP:
$_POST["DATA"] = array("name"=>"Koko bongo","age"=>12,"graduation_date"=>"12/06/1986");
and we define a validation array, like this:
$validator= array("name"=>"string","age"=>"integer","graduation_date"=>"date");
I have a configuration for each table which makes this automated but you can do it customly inplace by having an evalAndFormatType function that works like this
function evalAndFormatType($value,$type) {
switch strtolower($type) {
case "integer":
$item = is_numeric($value) && !strstr($value,DECIMAL_SEPARATOR) ? intval($item) :false;
break;
case "Date":/*we suppose that somehow we now the order, how you do it it is your decision: configuration array,constants etc*/
$check = explode(DATE_SEPARATOR,$value);
$item = sizeof($check) == 3 && checkdate(intval($check[1]),intval($check[0]),intval($check[2])) ? $check[2]."-".$check[1]."-".$check[0] : false;
break;
default:
throw Exception("Unknown type ".$type);
break;
}
return $item;
}
now, in your code you can say
$_DATA = $_POST["DATA"]; // the previously defined array
$errMsg = array();
foreach($_DATA as $k=>$v) {
$_DATA[$k] = evalAndFormat($v,$validator[$k]);
if($_DATA[$k] === false) {
$errMsg[$k] = "requires type ".$validator[$k];
}
}
if(empty($errMsg)){
$sql= ....WHATEVER USING THE INFO
} else {
return $errMsg;
/*this can be used to show errors nicely near your text boxes by parsing the expected keys or sending it by JSON etc
or
you could create a string out of it by using locale data that you might have which could output something like
Required fields: Graduation date[invalid type],Name,Age ... etc
"/
I hope this answers your question and also explains my "strange" approach on it.
}

drupal------how to output it

this is the code in my module file. if i only want to print the second or the third value or another value., how should i do?
function alterlink_address(){ //page callback function
$sql = db_query("SELECT field_link_url FROM {content_type_address}");
while ($q = db_fetch_object($sql)){
return $q->field_link_url.'<br>';
}
}
I'm no drupal expert and there will surely be a more economic way, but this will still work:
function alterlink_address(){ //page callback function
$sql = db_query("SELECT field_link_url FROM {content_type_address}");
while ($q = db_fetch_object($sql)){
$results[] = $q->field_link_url.'<br>';
}
return $results[0]."<br />";
}
Where the 0 in square brackets is the number (starting from 0) of the result you want to return.
A couple of notes:
a correct indentation can save lives;
getting a plethora of results from the database and displaying just a few of them is a nice method to awaken Cthulhu. I suggest you take a look at the drupal docs to get directly just the results you need.

Process for pulling data from a sql database

I want to make a program that pulls objects from a sql database and processes the objects against a set of functions before returning the data to the user.
It will work like this:
User specifies a date range in a javascript form.
The date range is sent to a php file on the server that converts it to
a sql query.
The sql query pulls all data in the database that matches the date
range, and stores each matching item and its associated information as a php
class in a temporary php file (see example below).
The main php program then processes each class in the temporary php file against a set of functions and returns the information to the user.
Example temporary php file:
class ice_cream
{
$temperature = 0;
$texture = 'soft';
}
class hard_candy
{
$temperature = 20;
texture = 'hard';
}
Example of Functions to process the classes against:
function will_it_break_dentures($class_name)
{
//$class_name is passed to the function based on the classes available in temp file
$food_type_class = new $class_name();
$damage_potential_temperature = $food_type_class->temperature;
$damage_potential_temperature = $food_type_class->texture;
if($damage_potential_temperature >= 15) && ($damage_potential_texture === 'hard')
{
print("Don't eat it");
}
}
Is there a more efficient/secure way to pull data from a database and process it against a set of functions? Is this the standard way to pull data from a database for processing? Item #3 seems suspect, but it's the best I could come up with. Any relevant informational resources on best practice are appreciated.
Your class definition should define the properties of the object, not the values. It should be defined statically, not dynamically at runtime. At runtime you create instances of this class and populate the data for each instance.
Try something like this:
class Food {
var $name;
var $temp;
var $texture;
// Constructor
public function food($name, $temp, $texture) {
$this->name = $name;
$this->temp = $temp;
$this->texture = $texture;
}
public function breaksDentures() {
if($this->temp >= 15) && ($this->texture === 'hard')
return true;
else
return false;
}
}
And use it like this:
function processFoods($daterange) {
$query = build_query_from_daterange($daterange);
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
$food = new Food($row['name'], $row['temp'], $row['texture']);
// Now $food is an instance of the Food class populate with the values
// from the db, e.g., 'ice cream', 0, 'hard'.
if $food->breaksDentures() {
print("Don't eat it");
}
}
}
P.S. You may want to brush up on your object-oriented concepts. Your question is a good one but indicates some confusion about OO basics.

Categories