PHP setting variable as string and then using it again - php

Could anyone help me with such issue:
I'm trying to make thing, that based on $_Post data I'm showing or not data in the Google tables. (I've removed unnecessary parts of code, that are not actual to this question)
currently, check looks like:
if(!empty($_POST['include_pm'])) {
$pm_script = "data.addColumn('string', 'PM');";
$t0 = ",'\".";
$t1 = '$row['."'".PM."'".']';
$t2 = ".\"'";
$pm_ent = $t0.$t1.$t2;
}
else
{
$pm = "";
$pm_script = "";
$pm_ent = "";
}
And in google visualization table it goes as :
<?php echo $pm_script; ?>
data.addRows([
<?php
foreach ($rows as $row) {
echo "['".$row['TYPE']."'".$pm_ent."],";
}
?>
]);
So basically, when $_POST is empty, nothing is included (as well in script), and it works pretty fine, as needed.
But I'm not able to make it work, when $_POST is not empty: as far as I was experimenting(this one is my last attempt), it printed in the data table exactly string value of the pm_ent value, so it wasn't working in the code as such but became really as a string.
Maybe someone could help me with this, so it would work dynamically - If it's not empty, PM row would be added to the data Rows? As I'm not so good at PHP, I'm having lack of knowledge, how to solve this...
Or maybe there is some smarter way how to do it?

$pm_script = "";
if(!empty($_POST['include_pm'])) {
$pm_script = "data.addColumn('string', 'PM');";
}
And in google visualization table it goes as :
<?php echo $pm_script; ?>
data.addRows([
<?php
foreach ($rows as $row) {
$pm_ent = "";
if( $pm_script !="")
{
$pm_ent =",'".$row['PM']."'";
}
echo "['".$row['TYPE']."'".$pm_ent."],";
}
?>
]);
Hope it will help..

Related

Using array from header in another page

Ok so I have an array "$landing" in my header.php, then in my page.php I include the header.php but for some reason when I call the 'Name' field in the array in the page.php: echo $landing['Name']; it just doesn't work.
this is how the array is being filled up, and calling it in the header works perfectly.
$landing = array();
while ($row = mysql_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing = $row;
}
}
To clarify, $row and $landing are both arrays, and both have multiple fields 'Name' 'Color' 'Info'.
What am I doing wrong here? Do I need to make it global somehow or what's going on?
The original code works somehow, now as the OP said in a comment.
But my old tips still hold:
Consider using MySQLi or PDO instead of the deprecated MySQL extension!
Why do you compare the dataset's column value on the client-side? You can do this on the MySQL side, it'll be faster!
You are, as ComFreek correctly stated, turning $landing into a string. Instead, if you're trying to add an entry to the landing array, use [] brackets which mean "add into new entry".
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing[] = $row;
}
}
I cant comment LS97 post, anyway you want to use $landing["Name"] you edit LS97 code into this:
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing["name"] = $row;
}
}
If you want to use multiple names, LS97 code is fine.
The problem is what they said. (Using $landing = $row, landing will be a string.)

Referencing a multidimensional array's elements based on a string without eval

Alright I'm working with a large multidimensional array which has more information in it than I need and I want to loop through it to filter the data which I'm interested in. Sadly this multidimensional array is produced dynamically and doesn't always contain the data I want, so I have to use logic like:
if(isset($ar['b']['ba']['baa'])){
echo '<h3>'.$ar['b']['ba']['baa'].'</h3>';
}
if(isset($ar['b']['ba']['baba'])){
echo '<h3>'.$ar['b']['ba']['baba'].'</h3>';
}
if(isset($ar['b']['ba']['babb'])){
echo '<h3>'.$ar['b']['ba']['babb'].'</h3>';
}
The above works great but its a bit messy-looking so I converted the above to:
$refAr=array();
$refAr[]='b->ba->baa';//3
$refAr[]='b->ba->bab->baba';//4
$refAr[]='b->ba->bab->babb';//5
The above looks a lot more nice and neat and is how I want to control the script in case I need to reference different keys in the future. The problem I am having is trying to use the above format to actually reference the array. I thought variable variables would work but apparently it fails. My second attempt using eval worked but I'm not very happy with my solution. This is where I need you guys to come in, is there a better way to do this? Here's my attempt below:
<?php
$ar=array(
'a'=>array('aa'=>1,'ab'=>2),
'b'=>array(
'ba'=>array('baa'=>3,'bab'=>array('baba'=>4,'babb'=>5),'bac'=>array('baca'=>6,'bacb'=>7)),
)
);
$refAr=array();
$refAr[]='b->ba->baa';//3
$refAr[]='b->ba->bab->baba';//4
$refAr[]='b->ba->bab->babb';//5
foreach($refAr as $ref)
{
$r=explode('->',$ref);
$r="\$ar['".implode("']['",$r)."']";
echo '<h1>'.$r.'</h1>';
echo '<h3>'.$$r.'</h3>';//undefined
eval('$t='.$r.';');
echo "<h3>$t</h3>";//works but uses eval, is there a better way?
}
You can try
$ar = array();
$ar['b']['ba']['baa'] = 3;
$ar['b']['ba']['bab']['baba'] = 4;
$ar['b']['ba']['bab']['babb'] = 5;
$refAr = array();
$refAr[] = 'b->ba->baa'; // 3
$refAr[] = 'b->ba->bab->baba'; // 4
$refAr[] = 'b->ba->bab->babb'; // 5
foreach ( $refAr as $ref ) {
$t = $ar;
foreach ( explode("->", $ref) as $v ) {
if (!isset($t[$v]))
break;
$t = $t[$v];
}
is_array($t) and $t = null;
echo "<h3>$t</h3>";
}
Output
345
I decided to answer my own question. This is what I wound up using:
<?php
//Sample PHP representation of dynamically-pulled JSON data from an untrusted source
$ar=array(
'a'=>array('aa'=>1,'ab'=>2),
'b'=>array(
'ba'=>array('baa'=>3,'bab'=>array('baba'=>4,'babb'=>5),'bac'=>array('baca'=>6,'bacb'=>7)),
)
);
//Reusable function
function resolveReference($ar,&$ref)
{
$t = $ar;
foreach ( explode('->',$ref) as $v )
{
if (!array_key_exists($v,$t)){$ref=null;return false;}
$t = $t[$v];
}
$ref=$t;
return true;
}
//The references I'm interested in but don't know if my dynamic data will contain these keys every time
$refAr=array();
$refAr[]='b->ba->baa';
$refAr[]='b->ba->bab->baba';
$refAr[]='b->ba->bab->babb';
$refAr[]='b->doesnt->exist';
foreach($refAr as $ref)
{
echo '<h1>'.$ref.'</h1>';
if(resolveReference($ar,$ref))
{
echo '<h3><span style="color:blue;">'.$ref.'</span></h3>';
}else{
echo '<h3><span style="color:red;">Alternative text for non-existent expected reference</span></h3>';
}
}

PHP JSON Array Formatting

Let me first start off, sorry for the confusing title. I didn't know how to exactly describe it but here goes. So I am querying a database for string. If there is only 1 result found then it is relatively easy to create an array, fill it with information, encode JSON and return that. I am confused as to when there are multiple results. The code below is what I am using but I highly doubt it is correct. I can't encode it into JSON format using my method which is what I need. If you can help at least point me in the correct direction, I would be more than grateful! Thank you!
PHP:
if ($action == 'profile') {
while ($pson = mysql_fetch_array($personQuery)) {
$typeSearch = 'profile';
$profQuery = mysql_query("SELECT * FROM tableName WHERE ColumnName LIKE '$query'");
$compQuery = mysql_query("SELECT * FROM tableName2 WHERE ColumnName LIKE '$query'");
if ($profQuery && mysql_num_rows($profQuery) > 0) {
$personQueryRows = mysql_num_rows($profQuery);
while ($row = mysql_fetch_array($profQuery)) {
if ($compQuery && mysql_num_rows($compQuery) > 0) {
while ($com = mysql_fetch_array($compQuery)) {
if (mysql_num_rows($profQuery) > 1) {
$compQueryRows = mysql_num_rows($compQuery);
if ($compQueryRows > 0) {
$compReturn = "true";
} else {
$compReturn = "false";
}
$nameArray = Array(
"success"=>"true",
"date"=>date(),
"time"=>$time,
"action"=>$action,
"returned"=>"true"
);
global $result;
for ($i=1;$i<=$personQueryRows;$i++) {
$nameResult[$i]=Array(
"id"=>$row['id'],
"name"=>$row['name'],
"gender"=>$row['gender'],
"comp"=>$row['company'],
"queryType"=>"profile"
);
$result = array_merge($nameArray, $nameResult[$i]);
}
$encodedJSON = json_encode($result);
echo $encodedJSON;
}
}
}
}
}
}
}
}
Returned JSON:
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"14321","name":"John Smith","gender":"male","comp":"ABC Studios, LLC.","queryType":"profile"}
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"292742","name":"John Smith","gender":"male","comp":"DEF Studios, LLC.","queryType":"profile"}
JavaScript error (when parsing JSON):
Uncaught SyntaxError: Unexpected token {
P.S. I am just getting started with PHP Arrays, and JSON formatting so I apologize if this is totally wrong. Still in the learning phase.
It looks like you're building up $nameResult[$i], but then you do:
$result = array_merge($nameArray, $nameResult[$i]);
You're doing that in each iteration of that for loop (once for each of the rows you got back), meaning that each time, you're clobbering $result.
After you finish that for loop, you then take whatever $result finally is (meaning the last $personQueryRows), and then json_encode it.
Looking at your other question (http://stackoverflow.com/questions/11257490/jquery-parse-multidimensional-array), it looks like what you should really be doing is before the loop where you go over $personQueryRows:
$output=$nameArray;
And then replace the array_merge line with:
$output[] = $nameResult[$i];
That last line will append the $result array onto the $output array as a new array member, meaning that it's nesting the array, which is what you'll need for your nested JSON.
Your code should look like this:
global $result;
$result = array();
.......
if ($action == 'profile') {
while{{{{{{{{...}}}}}}}}}}}
$encodedJSON = json_encode( $result );
echo $encodedJSON;
}

convert array to object in php

In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).

Output a result of an SQL query to a PHP array

I'm new to OOP in PHP, is that to seems correct ?
class whatever {
Function Maths() {
$this->sql->query($requete);
$i = 0;
while($val = mysql_fetch_array($this)) {
$tab[i][average] = $val['average'];
$tab[i][randomData] = $val['sum'];
$i=$i+1;
}
return $tab;
}
I want to access the data contained in the array
$foo = new whatever();
$foo->Maths();
for ($i, $i <= endOfTheArray; i++) {
echo Maths->tab[i][average];
echo Maths->tab[i][randomData];
}
Thank you ;)
EDIT: i want to output the result of the SQL query as an array, so i can access it from outside the class
In the interest of helping you out, here are some modifications. Please hear this, though: a lot of this might not make sense without a good background in PHP or OOP in general. You should look at #webbiedave's link.
class whatever {
static function maths() {
$tabs = array();
$results = $this->sql->query($requete);
while($val = mysql_fetch_array($this)) {
$tabs = $val;
}
return $tabs;
}
This fixes syntax errors and logic errors (for instance, the creation of the $results variable to hold the SQL query run).
I made the maths method static, since there's really no need to instantiate a whatever() object with this current example.
Here are some modifications to how this would be used:
$results = whatever::maths();
foreacho ($results as $result) {
echo $result['average'];
echo $result['randomData'];
}
Since maths() returns something, you need to store that in a variable; simply calling it, as you did previously, doesn't do anything.
That convoluted for loop can be replaced with a foreach loop.
Please check out PHP OOP basics:
http://www.php.net/manual/en/language.oop5.basic.php
Edit: Thanks for cleaning up the code. Try something along the lines of:
$tabs = array();
while($val = mysql_fetch_assoc($result)) {
$tabs[] = $val;
}
And:
$foo = new whatever();
$tabs = $foo->Maths();
for ($tabs as $tab) {
echo $tab['average'];
echo $tab['randomData'];
}
http://www.php.net/manual/en/language.oop5.basic.php

Categories