I would like to select a specific line of an object that have been created using json_encode function from a php array.
while($locations=$req->fetch()){
$t = $locations->titre;
$la = $locations->latitude;
$lo = $locations->longitude;
$typ = $locations->type;
$ep = $locations->couleur;
$matrice[$i] = array($t, $la, $lo, $ep);
$i=$i+1;
}
var locations = <?php echo json_encode($matrice); ?>;
locations[0] = ['ma position actuelle', 0, 0, 0];
//console.log(Object.keys(locations));
//console.log(locations);
var centerLat=0.0, centerLong=0.0;
for (var i=1; i<Object.keys(locations).length; i++) {
centerLat+=locations[i][1];
centerLong+=locations[i][2];
}
I would like to select the second and the third element of "locations" but the syntax inside the loop is wrong. Does anyone has an idea.
Thank you
First you should do:
var locations = JSON.parse(<?php echo json_encode($matrice); ?>);
Then console.log(locations.toString()); to check your data
After, I think you're looking for Array.prototype.unshift() to add elements at the beginning of the array:
locations.unshift(['ma position actuelle', 0, 0, 0]);
(locations[0] = ['ma position actuelle', 0, 0, 0] just replace first item of the array)
then change you for loop
for (var i=1; i<Object.keys(locations).length; i++)
for
var i = 1, ln = locations.length;
for (i;i<ln;i++)
You can access any item in an JSONArray (or any Array) in JS like this:
object[i]
In your example, if you wanna get the second and third element:
for (...) {
var longitude = locations[i][1];
var latitude = locations[i][2];
}
But, I suggest that you use keys and make JSONObjects instead of just JSONArrays, like this:
$locations = array();
while($locations=$req->fetch()){
$location = array(
'titre' => $locations->titre,
'latitude' => $locations->latitude,
'longitude' => $locations->longitude,
... etc
);
$locations[] = $location;
}
That way you'll end up with a nice JSONArray filled with JSONObjects and you can call them from JS like this:
//locations is a JSONArray
var locations = <?php echo json_encode($matrice); ?>;
//locations[0] is a JSONObject
var latitude = locations[0].latitude;
var latitude = locations[0].longitude;
I created a code that retrieves data from a DB using ajax and Json in Javascript and PHP. In the end, a dropdown list is populated with the data from the query. It worked fine until I added the bind_parameter functions to prevent SQL-injection. Any idea what I am doing wrong here?
JavaScript:
function getCompetitie()
{
seizoen = $("#Seizoen-text").val();
$.ajax({
type:'POST',
url:'get_competitie.inc.php',
dataType: 'json',
data: {seizoen: seizoen},
success: function(response){
$("#Competitie-list").empty();
$("#Competitie-list").append("<option>Competitie</option>");
var len = response.length;
alert(len);
for(var i = 0; i < len; i++){
var comp = response[i]['Competitie'];
$("#Competitie-list").append("<option value='"+comp+"'>"+comp+"</option>");
}
}
});
}
PHP code WITHOUT binding parameters (works fine):
<?php
include "includes/dbh.inc.php";
$sql = "SELECT DISTINCT Competitie FROM kalender WHERE Seizoen='".$_POST['seizoen']."' ORDER BY Seizoen DESC;";
$result = mysqli_query($conn, $sql);
$result_array = array();
while($row = mysqli_fetch_array($result)){
$competitie = $row['Competitie'];
$result_array[] = array("Competitie"=>$competitie);
}
echo json_encode($result_array);
?>
PHP code WITH binding parameters (does not work) :
<?php
include "includes/dbh.inc.php";
$seiz= $_POST['seizoen'];
if (empty($seiz)) {
exit ();
}
else {
$sql = "SELECT DISTINCT Competitie FROM kalender WHERE Seizoen=? ORDER BY Seizoen DESC;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt,$sql)) {
exit ();
}
else {
mysqli_stmt_bind_param($stmt, "s", $seiz);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$result_array = array();
while($row = mysqli_fetch_assoc($result)){
$result_array = array();
$seizoen = $row['Seizoen'];
$result_array[] = array("Seizoen"=>$seizoen);
}
mysqli_stmt_close($stmt);
echo json_encode($result_array);
}
else {
exit ();
}
}
}
?>
All I seem to be getting is "undefined" in the dropdown box. Anybody a suggestion where I went wrong? Thanks in advance!
You are selecting the column Competitie in $sql = "SELECT DISTINCT Competitie..
So, fix this:
//if ($row = mysqli_fetch_assoc($result)) { //remove this line
$result_array = array();
while($row = mysqli_fetch_assoc($result)){
$competitie = $row['Competitie'];
$result_array[] = array("Competitie"=>$competitie);
}
mysqli_stmt_close($stmt);
echo json_encode($result_array);
Or select the Seizoen column also.
I am creating an internal web tool that inserts data into a database. I was trying to find out how to create a three-tier dropdown selection, where I would insert the third dropdown's value into the DB.
I stumbled across this answer here:
Populate another select dropdown from database based on dropdown selection
But was done as a two tier dropdown.
My php code is this:
<?php
require 'connect.php';
$query = "SELECT customer_id,customer FROM schema.customer";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$categories[] = array("customer_id" => $row['customer_id'], "customer" => $row['customer']);
}
$query = "SELECT contract_id, customer_id, contract FROM schema.contract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subcats[$row['customer_id']][] = array("contract_id" => $row['contract_id'], "contract" => $row['contract']);
}
// Third dropdown which isn't originally included with the previous answer
$query = "SELECT subcontract_id, contract_id, subcontract FROM schema.subcontract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subsubcats[$row['contract_id']][] = array("subcontract_id" => $row['subcontract_id'], "subcontract" => $row['subcontract']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
$jsonSubSubCats = json_encode($subsubcats);
?>
Now, the given answer was this:
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
//Below wasn't part of the answer
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var catSelect = this;
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
But I needed help with the third tier options based from the second dropdown selection. Thanks in Advance. :)
Was able to figure it out.
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect")
subcatSelect.onchange = updateSubSubCats;;
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
function updateSubSubCats(){
var subsubcatSelect = this;
var contract_id = this.value;
var subsubcatSelect = document.getElementById("subsubcatsSelect");
subsubcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subsubcats[contract_id].length; i++){
subsubcatSelect.options[i] = new Option(subsubcats[contract_id][i].subcontract,subsubcats[contract_id][i].subcontract_id);
}
}
</script>
Summary of problem: I have a mysql table with some data, I use some phpcode to display the data to an html page, to setup JavaScript variables before a page loads. The loop seems to work fine with one exception, the first row of the table gets dropped or doesnt show. I cant figure out why, is there a small bit of logic Im missing?
I have a mySQL table here:
http://gyazo.com/ac75247b1a3f11f59721f03ff9c80d08
and some php code to display it here:
//...
$sql = "SELECT * FROM ".TABLE_CALCULATOR." WHERE calculation_status = 'A'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
if(count($num_rows) > 0 ){
while ($row = mysql_fetch_assoc($result)) {
$calculator_data[] = $row;
}
}else{
// Send Notication to admin Calculator not set
}
//...
<?php
if(!empty($calculator_data)){
foreach($calculator_data as $k => $v ){
if($v['name_value'] == 'perWinPriceMatrix'){
$per_win_matrinx = explode(",", $v['calculation_values'] );
$per_win_matrinx_final = array_chunk($per_win_matrinx, 5, true);
foreach($per_win_matrinx_final as $key => $values ){
$var[$key] = $key.':['.implode(',',$values).']';
}
?> var <?php echo $v['name_value'] ;?> = <?php echo "{".implode(",", $var)."}";?>;<?php echo "\n";
}else{
?> var <?php echo $v['name_value'] ;?> = [<?php echo $v['calculation_values'] ;?>];<?php echo "\n";
}
}
}
?>
this is the output:
var tax_bronze2 = [30,20,20,5,0];
var tax_bronze3 = [30,20,20,5,0];
var tax_bronze4 = [25,20,20,5,0];
var tax_bronze5 = [25,20,20,5,0];
var tax_silver1 = [35,30,30,5,0];
var tax_silver2 = [30,20,20,5,0];
var tax_silver3 = [30,20,20,5,0];
var tax_silver4 = [30,20,20,5,0];
var tax_silver5 = [30,20,20,5,0];
var tax_gold1 = [70,50,30,10,0];
var tax_gold2 = [60,40,20,8,0];
var tax_gold3 = [60,40,20,8,0];
var tax_gold4 = [60,40,20,8,0];
var tax_gold5 = [60,40,20,8,0];
var tax_platinum1 = [100,75,40,10,0];
var tax_platinum2 = [80,65,40,10,0];
var tax_platinum3 = [80,65,40,10,0];
var tax_platinum4 = [80,65,40,10,0];
var tax_platinum5 = [80,65,40,10,0];
var tax_diamond1 = [0,0,0,0,0];
var tax_diamond2 = [120,85,50,20,0];
var tax_diamond3 = [120,85,50,20,0];
var tax_diamond4 = [120,85,50,20,0];
var tax_diamond5 = [120,85,50,20,0];
var perWinPriceMatrix = {0:[4,4,4,4.5,4.75],1:[5,5.3,5.7,6.2,6.2],2:[7.8,8.6,9.7,10.8,11.8],3:[13,15,17,18,18],4:[19,21,25,30,40]};
var price_matrix = [19,20,20,20,32,24,24,24,24,42,46,51,53,56,60,60,65,74,79,140,186,214,242,298];
var provisionalPrice = [60,80,9.25,13,1.3,0.75];
question: Why is output missing a row?
delete $row = mysql_fetch_array($result); this line fetch row #1