Solving extra apostrophe from php to java - javascript

I am doing a project on converting a database using sql, php and java for making a website. I have this inside my database:
echo's echos
sound wall
this is my code:
var places = [<?php
$mysqli = new mysqli("localhost", "root",null, "cdcol");
$stmt = $mysqli->prepare("select Name,Latitude,Longitude from food");
$stmt->execute();
$stmt->bind_result($name,$lat,$lon);
$space="
";
while ($stmt->fetch()) {
echo "['$name',$lat,$lon,$i,'Food',20],$space";
$i++;
}
$stmt->close();
$mysqli->close();
?>];
and using php, I have make I've taken out the two data but it has cause the problem with the '
the data display before will be
var place = [['echo's echos', lat, lon, 13, 'Food', 20],
['sound wall', lat, lon, 13, 'Food', 20]];
which the array will be use for some purposes

Try loading the values in php array using
array_push
Then pass the array as json encoded format, use json_encode
so the assignment to place will be made as
var place = <?php echo json_encode($placearray); ?>
Hope it helps!

your result looks like JSON, so you could put all your variables into a PHP array and let json_encode() do the escaping for you:
$placesJson = array();
while ($stmt->fetch()) {
$placesJson[] = array($name, $lat, $lon, $i, 'Food', 20);
$i++;
}
$places = json_encode($placesJson);

Related

How can I add more than 3 rows to my json output? [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I have a mysqli query which I need to format as JSON for a mobile application.
I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)
$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);
// create xml format
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);
// add node for each row
while($row = $stmt->fetch()) :
$occ = $doc->createElement('data');
$occ = $root->appendChild($occ);
$child = $doc->createElement('section');
$child = $occ->appendChild($child);
$value = $doc->createTextNode($title);
$value = $child->appendChild($value);
endwhile;
$xml_string = $doc->saveXML();
header('Content-Type: application/xml; charset=ISO-8859-1');
// output xml jQuery ready
echo $xml_string;
Simply create an array from the query result and then encode it
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
$result = $mysqli->query("SELECT * FROM phase1");
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);
output like this:
[
{"id":"31","name":"product_name1","price":"98"},
{"id":"30","name":"product_name2","price":"23"}
]
If you want another style, you can change fetch_assoc() to fetch_row() and get output like this:
[
["31","product_name1","98"],
["30","product_name2","23"]
]
Here's how I made my JSON feed:
$mysqli = new mysqli('localhost', 'user', 'password', 'myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
As mentioned, json_encode will help you. The easiest way is to fetch your results as you already do it and build up an array that can be passed to json_encode.
Example:
$json = array();
while($row = $stmt->fetch()){
$json[]['foo'] = "your content here";
$json[]['bar'] = "more database results";
}
echo json_encode($json);
Your $json will be a regular array with each element in it's own index.
There should be very little changed in your above code, alternativly, you can return both XML and JSON since most of the code is the same.
There is one essential thing about JSON - the data must be UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.
The rest is as silly as any other database operation
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$db->set_charset('utf8mb4');
$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $db->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);
I managed to run this code:
<?php
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
If you have mysqlnd extension installed + enabled in php, you can use:
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$result = $mysqli->query("SELECT * FROM phase1");
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
mysqli::fetch_all() needs mysqlnd driver to be installed before you
can use it.

How do I get values from a PHP array to a Javascript Array?

So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. First I just echo'd the array like this:
PHP:
<?php
$exampleArray = ["212", "33", "7"]
?>
and JS:
<script> var jExampleArray = <? echo json_encode($exampleArray);?>; </script>
And then I used jExampleArray in my bar chart code. Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page. I thought about using Ajax and what not but it just didn't work for me. I got it to alert me the array, but was not able to fill a Javascript array with it.
I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. Luckily I managed to at least understand the code I wrote/copied.
Edit: [] for a JS array not {}
Your syntax for creating the PHP array is incorrect.
Use the function json_encode to transform PHP arrays into Javascript arrays and objects.
<?php
$arr = ['hello', 'world', 'foo', 'bar'];
$obj = ['hello' => 'world', 'foo' => 'bar'];
echo 'var Array = ' . json_encode($arr) . PHP_EOL .
'var Obj = ' . json_encode($obj, JSON_FORCE_OBJECT) . PHP_EOL;
Will result in the following:
var Array = ["hello","world","foo","bar"]
var Obj = {"hello":"world","foo":"bar"}
Some pseudo code to show how you might accomplish the stated goal
$data=array();
while( $rs=$db->fetch() ){
$data[]=array(
'field_1' => $rs->field_1,
'field_2' => $rs->field_2,
'field_3' => $rs->field_3
);
}
$json=json_encode( $data );
<script>
<?php
echo "var jExampleArray={$json};";
?>
/* rest of barchart code */
</script>
If the PHP array is available at page load use:
<?php
$phpArray = array('data1' => 2, 'data2' => 3);
?>
<script>var arr = <?php echo json_encode($phpArray); ?>;</script>
To retrieve PHP array in JS after page load using ajax:
var arr = JSON.parse(responseArray);

converting data from sqlite PHP

I have a number of coordinates stored in a sqlite database. I need these coordinates to be used in a heatmap on leaflet.
I'm using the following plugin: https://github.com/Leaflet/Leaflet.heat
The data needs to be in the following format:
var addressPoints = [
[52.344161, 4.912279],
[52.342425, 4.913038],
[52.342034, 4.913256],
[52.341987, 4.912462]];
I extract the data from the sqlite database in PHP using:
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
while ($row = $results->fetchArray()) {
echo json_encode($row['coord']);
}
$db->close();
The data retrieved looks like:
"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"
How can I get the SQLite data inserted in 'var addressPoints' in a correct manner?
Thansk in advance,
JWB
If the data follows that same format with the quotes at start and end and double quotes in between pairs the following should produce an array with the pair as an entry.
$data='"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"';
$pairs=explode('""',trim($data,'"'));
print_r($pairs);
output:
Array
(
[0] => 52.344161000, 4.912279000
[1] => 52.342425000, 4.913038200
[2] => 52.342034000, 4.913256000
[3] => 52.341987000, 4.912462000
[4] => 52.342336000, 4.912106000
)
You could alter your initial php however which would produce different data
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
$json=array();
while( $row = $results->fetchArray() ) {
$json[]=$row['coord'];
}
$db->close();
$json=json_encode( $json );
echo $json;
if you needed this without the quotes around the values...
$json=str_replace('"','',$json);
in the javascript then you could do:
echo "var addressPoints={$json};";

Populating a JavaScript array with MySql data

I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:
var $name = "Foo",
$x = 10,
$bar =
<? php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>;
EDIT: I then post this to a .php file, and print the returned data:
$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
$('body').html(data);
window.print();
setTimeout("location.reload(true)", 500);
});
However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?
var $name = "Foo",
$x = 10,
$bar = "
<?php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>";
You have a superfluous space inside the PHP opening tag:
<? php
^--- this shouldn't be there
As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.

php file to php array to js array - as array of arrays

...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>
How can I modify the above code that gives me this output (an array of objects methinks?)
var javascript_array = [
{"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
{"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
.... ]
to give me this... (an array of arrays?)
var javascript_array = [
["Hermosa Beach",33.860069,-118.398784],
["San Jose",34.694628",-118.398784],
.... ]
without a bunch of foreaching's...
Use MYSQLI_NUM instead of MYSQL_ASSOC when you call mysqli_fetch_all(). Then the rows will be indexed arrays instead of associative arrays.
Although I don't know why you would want the array to be like this. Arrays should be used for uniform data, objects should be used for heterogeneous data.
thanks, this works and is very lean...
<?php
$query = "SELECT * FROM file";
$result = $con->query($query);
// Fetch all rows and return the result-set as an associative array:
// using numeric keys for the array, instead of creating an associative array.
$php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>
<script type='text/javascript'>
<?php
// create a JSON representation of a value that javascript will understand
$js_array = json_encode($php_array);
// dump json object into javascript variable 'locations'
echo "var locations =" . $js_array . ";\n";
?>
</script>

Categories