I have an array of markers coded into a web page and I use them to generate markers for a google map in the form of
generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]);
So now am attempting to retrieve marker positions from a database so I attempted to use the code below to do so
getmkrs(
<?php
$db_con = mysql_connect("localhost",'root','');
mysql_select_db("db_name",$db_con);
$query_db = "Select * From table_name";
$result = mysql_query($query_db, $db_con);
$joiner = '';
?>
var_markers = [<?php while($row = mysql_fetch_assoc($result)):?>
<?= $joiner ?>
[<?= $addslashes($row['Row1']) ?>, <?= $row['Row2'] ?>, <?= $row['Row3'] ?> ]
<?$joiner = ','?>
<?php endwhile; ?>];
);
But Ultimately the page turns up blank, not even the map shows up. I am trying to replicate the above array which I coded into the web page. So my question is how can I efficient generate markers using data from a databse
For the love of god, don't cobble together JSON by hand interspersed in Javascript code. Create a sane data structure in PHP and encode it using json_encode:
<?php
$db_con = mysql_connect("localhost", 'root', '');
mysql_select_db("db_name", $db_con);
$query_db = "SELECT * FROM table_name";
$result = mysql_query($query_db, $db_con);
$markers = array();
while ($row = mysql_fetch_assoc($result)) {
$markers[] = array($row['Row1'], $row['Row2'], $row['Row3']);
}
?>
<script>
var markers = <?php echo json_encode($markers); ?>;
generateMarkers(markers);
</script>
Related
basically what I've been trying to do is with PHP get a integer from MySQL after that is done, using JavaScript get the integer that PHP has and display it on HTML
<?php include('ConnectionCode.php');
$conn = mysqli_connect($svr, $usr, $pwd, $db) or die("Could not connect " . mysql_error());
$sql = "SELECT RetailPrice FROM WebHosting_PricingCOP WHERE id='32402' LIMIT 1";
$result = mysqli_query($conn, $sql);
$price = mysqli_fetch_array($result);
echo json_encode(number_format($price['RetailPrice'],0,".",","));
mysqli_close($conn)
?>
the code above will connect to the Database and get the value 59,347
now I'm trying to move this single value from PHP to Javascript in order to display it on HTML
<script type="text/javascript">
var PriceValue = "<?php echo json_encode($price) ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
I have gone through many discussions and options here and there and still cant figure out to make it work, when i try to run the html it doesn't display anything
I would greatly appreciate your input
Update:
You may also have a problem with using json_encode inside of "" quotes.
var PriceValue = "<?php echo json_encode($price) ?>";
Instead, use:
var PriceValue = <?php echo json_encode($price) ?>;
or
var PriceValue = <?php echo $price ?>; // if $price is not an object
Note:
To debug this, check the generated HTML source to see what JavaScript you are actually generating.
$price needs to be in the same scope when you try to generate JS.
http://phpfiddle.org/main/code/aeav-gb1w
<?php
$price = 2523525;
?>
<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
However, it is going to be preferable for you to use your PHP file as an API endpoint instead of mixing your PHP and JavaScript together.
I'm trying to create a D3.js chart that requires data from a MySQL database. The chart is made using JavaScript, but I want to replace the values with the database value.
This works if I only try to input one value using PHP, but not if I add any more.
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
]; // This works
The above works, however, this doesn't:
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
{ name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data2"].""; } ?>}
]; // Adding another PHP value stops the entire chart from working (it works if I use a non-PHP second value).
I also attempted to just use one single while loop for all data, but that didn't work either.
<?php $connect = mysqli_connect("host", "user", "pass", "db");
$query = "SELECT data1, data2 FROM database WHERE x = y;
$result = mysqli_query($connect, $query); ?>
I know for sure that the data isn't the issue. I've tried the same thing on Google Charts and it worked without issue.
#create an array for the objects
$datasets=array();
#very unclear if your code fetches one or more rows,
#it seems one row with dataX fields
$row = mysqli_fetch_array($result);
#So we go over it
foreach($row as $field => $value) {
#create an object that becomes later {name:'abc',percent:'12'}
$obj = new stdClass();
$obj->name = $field;
$obj->percent=$value;
#collect it in the array,
#it becomes lates [{name:'abc',percent:'12'},{...},{...}]
$datasets[] = $obj;
}
#parse the data into the javascript part of the html content
?>
var datasets = <?php print json_encode($datasets);?>;
<?php
Hopefully, you can work with this.
If this is the real code you are using then the first bit of PHP consumes all of the resultset held in $result therefore there is nothing returned in the second bit of PHP
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
// $result has already been fully consumed
{ name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data2"].""; } ?>}
];
I am working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);
befora I ask this i tried every solution on google and here on stackoverflow.
So in my js file I have this
var locations = [
['Name','Country','City','lat','lng'],
['Name','Country','City','lat','lng'],
];
When i wrote this in file manually my mapp shown locations but I need to generate content of locations variable from mysql in php, is there something that I missing.I tried with ajax,console.log...etc
My PHP file
$result = mysqli_query($link, "SELECT hospital_name,country,city,lat,lng FROM hospitals");
$to_encode = array();
while($row = mysqli_fetch_row($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
I tried this but no success
$.getJSON( "process.php", function( json ) {
var locations = json;
});
I just switched your mysqli_fetch_row to mysqli_fetch_array
$result = mysqli_query($link, "SELECT hospital_name,country,city,lat,lng FROM hospitals");
$to_encode = array();
while($row = mysqli_fetch_array($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
Ive been trying this for hours now but it wont quite get there.
I have a database which amongst other things contains geocodes, lat and lon. I have accessed these using the following PHP
<?php
mysql_connect("localhost", "tompublic", "public") or die(mysql_error());
mysql_select_db("first_section") or die(mysql_error());
$data = mysql_query("SELECT geo_lat, geo_lon FROM first_page_data")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)){
$lat[] = $row['geo_lat'];
$lon[] = $row['geo_lon'];
}
?>
These values in $lat and $lon then need to be put into an array in a javascript function like so:
var latit = [];
var longi = [];
latit = '<?php echo $lat[]; ?>';
longi = '<?php echo $lon[]; ?>';
But it wont work! Any ideas?
Try:
var latit = <?php echo json_encode($lat); ?>;
var longi = <?php echo json_encode($lon); ?>;
Edit: Also, the mysql_ functions are deprecated.
You could try this:
var latit = [<?php echo implode(",",$lat) ?>];
var longi = [<?php echo implode(",",$lon) ?>];
First thing is first try to switch to MySQLi due to the fact that Mysql is depreciated.
But try
var latit = <?php echo json_encode($lat); ?>;
var longi = <?php echo json_encode($lon); ?>;
You can either do as #Robbert stated
OR
Using php json_encode convert it to JSON string and you need to JSON.parse() it to convert it to javascript object
var latit = JSON.parse("<?php echo json_encode($lat); ?>");
var longi = JSON.parse("<?php echo json_encode($lon); ?>");
JavaScript arrays are created using a comma separated list surrounded by brackets
var latit = [];
To use your PHP values
var latit = [<?PHP echo implode(",",$lat); ?>];
This assumes your values are numbers. If not, you'll need to include quotes.
var latit = ['<?PHP echo implode("','",$lat); ?>'];
Finally, json_encode is a good option as many of the other answers indicate.
Try this:
<?php
mysql_connect("localhost", "tompublic", "public") or die(mysql_error());
mysql_select_db("first_section") or die(mysql_error());
$data = mysql_query("SELECT geo_lat, geo_lon FROM first_page_data")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)){
$lat[] = $row['geo_lat'];
$lon[] = $row['geo_lon'];
}
echo '
<script type="text/javascript">
var latit = '.json_encode($lat).';
var longi = '.json_encode($lon).';
</script>
';
?>