How to get rid of empty values when adding string in php - php

I have something like this:
public function options()
{
$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It gives me a list of options from the DB, but it also gives me a null value at the top.
if I write it like this:
public function options()
{
//$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out = '';
$out .= '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It doesn't give me the null value but it only returns one value.
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
In this line if I don't add an , it gives me an error message, This because I have $out = ''; at the top. Now can you guys give me an idea how can I get all the values from the DB without the empty value at the beginning.
I also have another question , why we use ;; (double semicolon) in this code:
$docs = $this->getAll();;

test $out to see if it has any length, if so add the comma and the line, otherwise just set it to be the line:
$out="";
foreach($docs as $key=>$doc){
if(strlen($out)){
$out.=',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}else{
$out='{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
}
as to your other question, er, you wrote the code, so why did you put a double semi-colon?

This is not the correct way to build JSON. First create an array, and use json_encode() on it.

I'd suggest using an array instead to hold the individual values, and using join to concatenate them together.
public function options()
{
$docs = $this->getAll();
// Create an empty array
$items = array();
foreach($docs as $key => $doc) {
// "Push" an item to the end of the array
$items[] = '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
// Join the contents together
$out = join(",", $items);
return $out;
}
Also, the double semi-colon is completely unnecessary.

Related

Highcharts Column Range - How to render series data stored in PHP variables?

I have problems when trying to render correctly the Highcharts column range table. I have all the necessary data stored in PHP variables. The problem is that I can't get the table rendered when passing this variables.
If I try to pass direct numeric data, then the table is rendered, so the issue is in the data field.
Here's my code:
<?php
if (!isset($divId)) {
$mt = microtime();
$mt = explode(" ", $mt);
$divId = "stacked_container_" . floor($mt[0] * 100000) . "_" . $mt[1];
}
?>
<div id="<?php echo $divId; ?>" class="col-mx-12"></div>
<?php
$title = $elements['title'];
$resources = $elements['series']['resources'];
$values = $elements['series']['values'];
$resourcesSeries = '';
$valuesMinSeries = '';
$valuesMaxSeries = '';
foreach ($resources as $key => $resource) {
$resourcesSeries .= '"' . $resource . '",';
$valuesMinSeries .= $values[$key][0] . ',';
$valuesMaxSeries .= $values[$key][1] . ',';
}
$globalNav = $view['nav'];
// Transforming strings into array type
$valuesMin = str_split($valuesMinSeries);
$valuesMax = str_split($valuesMaxSeries);
$globalNav->addScriptJS("
$(document).ready(function () {
$('#" . $divId . "').highcharts({
chart: {
type: 'columnrange'
},
title: {
text: '" . $title . "'
},
xAxis: {
categories: [" . $resourcesSeries . "]
},
yAxis: {
title: {
text: 'range'
}
},
series: [{
data: [
[<?php echo $valuesMin[0]?> , <?php echo $valuesMax[0]?> ]
]
}]
});
});
");
?>
In this example I'm trying to display only the first element of $valuesMin and $valuesMax.
The final aim is to render all the data, so I need to implement a foreach too.
You appear to be duplicating your resources array, by calling it as both your $resources variable, and your $values variable:
$resources = $elements['series']['resources'];
$values = $elements['series']['resources'];
Which I will assume should be something like:
$resources = $elements['series']['resources'];
$values = $elements['series']['values'];
I have found a solution to the problem. This is how:
//The result will be in the $data variable
$data = '';
foreach ($resources as $key => $resource) {
$resourcesSeries .= '"' . $resource . '",';
$valuesMinSeries .= $values[$key][0] . ',';
$valuesMaxSeries .= $values[$key][1] . ',';
$data .= "[".values[$key][0]. "," .$values[$key][1]. "],";
}
And in the series field:
series: [{
data: [ " .$data. " ]
}]
Hope this will help!

PDO: UPDATE not working

I wrote some code to update a mySQL table via php/PDO.
But it is not working and I just can't figure out where my mistake is.
The execute() returns true, but the changes never actually show up in the table.
My code looks pretty much like this:
$columnObject = array(
"emailAddress"=>"aaa#aaa.com",
"passwordHash"=>"56bj5g63j4g57g567g5k75jh7gk4g74j5hg67",
"name"=>"qweqweqwe",
"lastActivity"=>4128649814
);
$knownColumnName = "emailAddress";
$knownColumnData = "aaa#aaa.com";
foreach ($columnObject as $columnName => $columnData) {
$pdoUpdateString .= $columnName . "=:" . $columnName . ",";
$pdoExecuteObject[$columnName] = $columnData;
}
$pdoUpdateString = rtrim($pdoUpdateString, ",");
$pdoExecuteObject['knownColumn'] = $knownColumnData;
$q = $this->hCon->prepare('UPDATE ' . $this->name . ' SET ' . $pdoUpdateString . ' WHERE ' . $knownColumnName . '=:knownColumn');
$q->execute($pdoExecuteObject);

Warning: prev() expects parameter 1 to be array, string given in

I'm trying to understand how to fix this error.
Warning: prev() expects parameter 1 to be array, string given in
Its in the if statement below. Is this happening since the first value doesn't have a previous and I need to deal with that condition? Weirdly this worked in regular .php but not in the framework I have it in now.
I'm trying to generate an XML file based on a result set returned for a query. (I'm open to better ideas)
$export.= '<Campaigns>';
while ($line = mysql_fetch_assoc($result) ) {
//echo '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= '<Campaign Info="' . $line['EmailTrackingNumber'] . '" EmailId="' .$line['EmailId'] . '">';
$export.= '<Emails>';
if (prev($line['EmailTrackingNumber']) == current($line['EmailTrackingNumber'])) {
$export.= '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= 'City="' . $line['City'] . '" ';
$export.= 'Zip="' . $line['Zip'] . '"';
}
$export.= '</Emails></Campaign>';
}
$export.= '</Campaigns></EmailTrackingData>';
//echo $export;
file_put_contents('DateOfFile-export.xml', $export);
This
prev($line['EmailTrackingNumber'])
is not an array but a string. This
prev($line)
makes more sense. It returns the array entry which is before the current entry of $line.
But I think you would like to compare the last record with the current record. But that does not work like this. You can only access the columns of the current record. You have to temporarly save your last record.
$export.= '<Campaigns>';
$lastLine = null;
while ($line = mysql_fetch_assoc($result)) {
//echo '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= '<Campaign Info="' . $line['EmailTrackingNumber'] . '" EmailId="' .$line['EmailId'] . '">';
$export.= '<Emails>';
if ($lastLine['EmailTrackingNumber'] == $line['EmailTrackingNumber']) {
$export.= '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= 'City="' . $line['City'] . '" ';
$export.= 'Zip="' . $line['Zip'] . '"';
}
$export.= '</Emails></Campaign>';
$lastLine = $line;
}
$export.= '</Campaigns></EmailTrackingData>';
//echo $export;
file_put_contents('DateOfFile-export.xml', $export);

PHP iteration foreach, omitting characters from last iteration

I'm tying to iterate through an array, assembling a string to return each time.
My question is how can I omit the comma on the last iteration of the array, or if there is only one element to the array? I'm not sure what this operation would be called as my coding skills are very rudimentary, so I've not had much luck searching for an answer. Even help knowing this basic detail would be much appreciated.
this is the result I'd like:
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' }
Note the lack of a trailing comma.
Below is the php Im using to generate the strings. It will always include a trailing comma which is causing me all sorts of greif.
//snipit
$i = 1;
$a = '';
foreach ($pages as $go)
{
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$a .= "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
$a .= ",\n";
$i++;
return $a;
}
Many thanks for your experience,
orionrush
$a[] = "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
and use it by
return implode(",\n", $a);
You should really use json_encode().
$data = array();
foreach ($pages as $go) {
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$data[] = array(
'image' => BASEURL . GIMGS . '/' . $go['media_file'],
'title' => $title . ', ' . $caption,
'url' => BASEURL . GIMGS . '/' . $go['media_file']
);
}
echo json_encode($data);
foreach ($pages as $go){
$return[] = json_encode($go);
}
return implode(",\n", $return);
do what you like in the foreach, the implode will comma separate the lines like you want
just chop the end off with substr:
return substr($a, 0, -3);

All symbols after "&" stripped

My query:
mysql::getInstance()->update('requests', array('response' => mysql_real_escape_string($_POST['status'])), array('secret' => $_POST['secret'])); ?>
If i wand to add string with "&" symbol, all symbols after "&" stripped.
Example:
string: !"№;%:?()_+!##$%^&()_+
in database i see only: !"№;%:?*()_+!##$%^
How to fix this?
update function, if anyone need:
function update($table, $updateList, $whereConditions)
{
$updateQuery = '';
foreach ($updateList as $key => $newValue) {
if (!is_numeric($newValue)) {
$newValue = "'" . $newValue . "'";
}
if (strlen($updateQuery) == 0) {
$updateQuery .= '`' . $key . '` = ' . $newValue;
} else {
$updateQuery .= ', `' . $key . '` = ' . $newValue;
}
}
return $this->query('UPDATE ' . $table . ' SET ' . $updateQuery . $this->buildWhereClause($whereConditions));
}
UPD:
echo mysql::getInstance()->getLastSQL() says:
UPDATE requests SET `response` = '!\"№;%:?*()_ !##$%^' WHERE `secret` = '52a4ab5f7f3e8491e60b71db7d775ee2'
so, problem with function update in mysql class?
Slaks, i need to use str_replace('&', '%28', $query); ?
You're probably passing a raw & character in the querystring, which causes everything after the & to be parsed as second parameter by PHP. (Before it gets into your variable)
You need to escape the & as %26.
EDIT: You need to escape it before you send it to the server. (When you make the HTTP request)

Categories