PHP array foreach while loop - php

I am trying to create javascript variable from php, this is what i want to get.
<?PHP echo "var color_name=[<?PHP echo $color_name;?>]"; //var color_name=["Green","Pink"];
<?PHP echo "var style_name=[<?PHP echo $style_name;?>]"; //var style_name=["Basic","Classic"];
this is my predefined_attributes table
this is what i have tried,
<?php
$predifined_qry = "SELECT attribute_column_name
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columnNames = Array();
while ($predifined_result_row = mysqli_fetch_assoc($predifined_result)) {
$columnNames[] = $predifined_result_row['attribute_column_name'];
}
now i can get the attribute_column_name in an array using a foreach loop, but i dont know how to get the attribute_column_value array in a variable like this $style_name, $color_name. please help.

First of all, if you only need 1 column, and the resource/data you get is not massive, you could just fetch all and extract the column
You could expose your php variables in js through JSON
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
?>
<script>
var columnames = JSON.parse("<?= json_encode($columnNames); ?>");
</script>
So now if we add in the other field :
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
$columnValues = array_column($predifined_rows, 'attribute_column_value');
// array_combines uses the first array as the key and the second as the value
$columns = array_combine($columnNames, $columnValues);
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
Edit
as in the comments, a key can only appear once in a hashtable/array
so we need to generate an array of values per key
<?php
$predifined_qry = "SELECT attribute_column_name, attribute_column_value
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columns = [];
while($row = mysqli_fetch_assoc($predifined_result)) {
if(!array_key_exists($row['attribute_column_name'], $columns)) {
$columns[$row['attribute_column_name']] = [];
}
$columns[$row['attribute_column_name']][] = $row['attribute_column_value'];
}
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>

1st : You need to select attribute_column_value column too
SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id
2nd : You need push both column value in two different array like this
while ( $predifined_result_row = mysqli_fetch_assoc($predifined_result) ) {
$color_name[] = $predifined_result_row['attribute_column_name'];
$style_name[] = $predifined_result_row['attribute_column_value'];
}
3rd : simple apply json_enocde and echo like this
<script>
var color_name=<?php echo json_encode($color_name); ?>;
var style_name=<?php echo json_encode($style_name); ?>;
</script>

$columnValues[] = $predifined_result_row['attribute_column_value'];
You can paste this code into your while loop
And dont't forget to get the need field form database:
$predifined_qry="SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id";

Related

Fill missing array values with zero if an array is empty in php mysql

i want to produce an array in this format [x,x,x] where each x is grouped by the addition of each retail id, however, for an empty array list, i want to have [x,x,0] assuming the third array is empty, instead of [x,x]
Below is my code
<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
// $outletname = $row['title'];
$outlet_id = $row['outletid'];
$outlets[] = $row['outletid'];
$amount = $row['amount'];
?>
<?php echo $outlet_id; ?>,
<?php } ?> ]
data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
$tot3 = $rowq3['totalsum'];
?>'<?php echo $tot3; ?>',<?php } ?>]
instead of having [3,4,2,3] and missing value not showing, i want to have [3,4,2,0,3] for the missing values, assuming 0 is the missing values
thanks
I have made a few changes. Mostly created a key value array depending on the id as the key, and setting all those values to sum => 0. Then, when you loop through all of the id and their sum's it changes the sum of the id's it finds.
It is untested, but should solve it. You may need to change the end. It was messy with all the opening and closing php tags.
<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
$outletsIdSum = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
// $outletname = $row['title'];
$outlet_id = $row['outletid'];
$outlets[] = $outlet_id;
$outletsIdSum[(int)$outlet_id] = 0;
$amount = $row['amount'];
?>
<?php echo $outlet_id; ?>,
<?php } ?> ]
data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
$outletsIdSum[(int)$rowq3['outletid']] = $rowq3['totalsum'];
}
echo "'" . implode( "','", $outletsIdSum );
?>]
add if condition on array
<?php
foreach(some_array as a)
{
if(a=="" or a==NULL)
a=0;
}
?>
this will check array element which is empty and then ,if it is empty it will assign array element to '0'
use this algorithm

Passing a variable from PHP-generated list to jQuery

I have a PHP-generated list:
<?php $row_number = 0;
while ($row = $result->fetch_object()) {
$row_number++;
$movie_id = $row->movie_id;
$title = $row->title;
if ($num_rows>0){ ?>
<p class='dragelement' id="<?php echo $movie_id; ?>">
<?php echo $title; ?>
</p>
<?php }
} ?>
and am trying to pass the variable 'movie_id' to jQuery for a drag-and-drop function using the id of the parent p selector:
var parent = $("p.dragelement").closest('p');
var movie_id = parent.attr('id');
The problem is that the resulting value of 'movie_id' is the first one of the list, not the current one.
Any ideas much appreciated!
How about last selector?
http://api.jquery.com/last-selector/
var parent = $(".dragelement:last");
var movie_id = parent.attr('id');

Dynamically add options to a list through a hidden iframe

I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
because my code works perfectly with:
<?php echo 'var oInner = document.createTextNode("Newoption");'; ?>
I don't know why createtextnode doesn't want to take my PHP var... I thought it could be a same origin policy since the database is located on a server outside my website.
I don't know.
You'll find enclosed the complete code:
In my HTML I have:
//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
<option value"France">France</option>
</select>
//Empty region list
<select name="regionm" id="regionm">
</select>
//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>
In my Javascript I have:
//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
var choixco = countrym.options[countrym.selectedIndex].value;
document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;
In my PHP region.php file, I have:
<?php
// Get my choice
$codepays = $_GET['choix'];
//Retrieve the regions corresponding to the country
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();
while($donnees)
{
// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);
?>
//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");
//Here is my big issue:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
oOption.value = "none";
oOption.appendChild(oInner);
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");
regionm.appendChild(oOption);
</script>
<?php
$donnees = $req->fetch();
}
$req->closeCursor();
exit();
?>
Have you tried simply oOption.innerHTML = '<?php echo $donnees["name"] ?>'; ?
I am suspecting that the indexed element cannot be found. But is all cases, this below should work.
<?php echo 'var oInner = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>
Found the solution: it was the php inserting \n so the solution is to do the following:
$desc= 'var oInner = document.createTextNode("'.$donnees["name"].'");';
$desc= str_replace("\n", "",$desc);
$desc= str_replace("\r", "",$desc);
Thanks everybody

Assigning a javascript array with PHP/Postgresql query values in a loop

So, I have a postgresql database and I'm querying a particular column's values and assigning each value to a javascript array. Now I have a javascript function which outputs this data on a map. When i test the array manually (Entering the respective array index one by one), it returns the output perfectly alright. But in a loop (When i want to output all at once), i can only see the first element's output. The rest of the array is simply ignored or there's an error. I don't understand where the mistake is. Here's the code:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyC0HZ81Ea8Jy8fJ6zm6_uvPp8UhLg5mczo&sensor=true"></script>
<script type="text/javascript" src="GeoJSON.js"></script>
<script type="text/javascript" src="polygon.js"></script>
<script type="text/javascript">
var geojson_Polygon = new Array();
function kaushik()
{
<?php
require("header.php");
$connection = pg_connect($full);
if(!$connection)
{
pg_close($connection);
}
$result = pg_query($connection, "SELECT ogc_fid, ST_AsGeoJSON(wkb_geometry), name FROM features");
if (!$result)
{
exit;
}
$i = 0;
while ($row = pg_fetch_row($result))
{
echo "\n";
echo "geojson_Polygon[$i] = $row[1];";
echo "\n";
echo "\n";
$i++;
}
?>
for (var j=0; j<317; j++)
{
showFeature(geojson_Polygon[j]);
}
}
</script>
If what you want to do is build a JS array , then just do:
<script type="text/javascript">
var data = [ <?php
// --- snip
$first = true;
while ($row = pg_fetch_row($result))
{
if ( $first )
{
$first = false;
}else{
echo ',';
}
echo $row[$i]
}
// ---- snip
?> ];
</script>
i think you should do
while ($row = pg_fetch_row($result))
{
echo "\n";
echo "geojson_Polygon[$i] = $row[$i];";
echo "\n";
echo "\n";
$i++;
}
otherwise the value is always the same
Just read the rows into a php array and then assign it as json.
<script>
...
var geojson_Polygon = <?php echo json_encode($all_rows); ?>;
....

Write to javascript array within php loop

I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.

Categories