Using PHP array in the JS code in PDO - javascript

I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.
I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_zagon = 1;
$id_kurat = 1;
$usid = 78;
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$gyvuliu_array = array();
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = $num;
}
$array_encode = json_encode($gyvuliu_array);
?>
<script>
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
I guess something is bad with the $num variable but I'm not sure.
EDIT:
I've changed the second for loop and it looks like it's working:
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m
EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

var gyvuliai_fermoje = <?php echo $array_encode; ?>;
You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array

Could You please try this once
$stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$row = $stmt1->fetch();
$array_encode = json_encode(explode(",",$row["nums"]));
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>

Try this
var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;

Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:
// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);
// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
// Creating a PHP array
$gyvuliu_array = array();
// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = (int)$num;
}
// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
for (var i = 0; i < gyvuliai_fermoje.length; i++) {
// Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
}
</script>
I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Related

storing a string from google webapp into an array

Suppose I would like to create an array on my JS code and push in a string coming from appscript htmlservice. How do I do it? The below does not work.
var array = [];
<? var data = getData(); ?>
<? for (var i = 0; i < data.length; i++) { ?>
<?= array.push(data[i]) ?>
<? } ?>
How about this modification? Please think of this as just one of several possible answers.
Modified script:
var array = [];
<? var data = getData(); ?>
<? for (var i = 0; i < data.length; i++) { ?>
array.push(<?= data[i] ?>); // Modified
<? } ?>
console.log(array);
Reference:
HTML Service: Templated HTML

how to use json_encode function of an array

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;

Javascript and PHP code doesn't function anymore after adding bind_parameter to prevent SQL-injection

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.

Third dropdown populated based from second and first dropdown selections

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>

PHP looped output of mySQL table is missing one row

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

Categories

Resources