Can anyone help me, I am very new to PHP, maybe the answer was very obvious.
I store users details and postcodes in the database, then I need to display the postcodes as markers on the google map using javascript (this was working).
But I was trying to display each user data on google map's info window, I am only be able to display the last row of the result, so all info windows were display the same record, not the individual data to that postcode.
I think I need to combine below two queries, but I don't know how. Because the postcode need to be implode to get "postcode" to show on map.
What I am trying to achieve:
postcode need to be ("AA4 1DD", "AB1 5CD","CC4 1BBs");
infowindow (Fred, 7 street, AA4 1DD);
What I have in the Database:
name Fred Ann John
address 7 street 8 road 4 line
postcode AA4 1DD AB1 5CD CC4 1BB
PHP:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$locations = $conn->prepare("SELECT postcode FROM tbl_data");
$locations->execute();
$lo= $locations->fetchAll(PDO::FETCH_COLUMN);
echo "'". $t = implode(' ,', $lo)."'";// working
//info window
$info_stmt = $conn->prepare("SELECT name, postcode FROM tbl_data, tbl_login WHERE tbl_data.user_id=tbl_login.user_id ");
$info_stmt->execute();
$result = $info_stmt -> fetchAll();
foreach( $result as $row ) {
echo $row[0];
/* echo "<pre>";
echo gettype($row[0]);
echo "</pre>";*/
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
Javascript:
var addressArray = new Array(<?php echo "'". $t = implode("' ,'", $lo)."'"; ?>); //postcodes working
var geocoder = new google.maps.Geocoder();
for (var i = 0; i < addressArray.length; i++) {
geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Click for more details'
});
//create info window
var infoWindow = new google.maps.InfoWindow({
content: "<p>Name: </p><?php echo $row[0].'<br />'.$row[1]; ?>"
});
Your issue is here:
content: "<p>Food Name: </p><?php echo $row[0].'<br />'.$row[1]; ?>"
You cannot mix JavaScript and PHP like this, and $row does not - or shouldn't - actually exist in this context due to it not being within the foreach statement or - if this is a seperate JS file - you have no corresponding context.
To achieve what you need, I'd suggest using AJAX and setting a GET request to a file which then returns an array which you can then use in your JavaScript.
You can read documentation on this here.
Note, $row should be used like this: $row['ColumnName'] (not just for readability).
For example: echo $row['address'];
Example Code (PHP):
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$locations = $conn->prepare("SELECT postcode FROM tbl_data");
$locations->execute();
$lo= $locations->fetchAll(PDO::FETCH_COLUMN);
echo "'". $t = implode(' ,', $lo)."'";// working
//info window
$info_stmt = $conn->prepare("SELECT name, postcode FROM tbl_data, tbl_login WHERE tbl_data.user_id=tbl_login.user_id ");
$info_stmt->execute();
echo $info_stmt->fetchAll();
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Then your JavaScript:
$(document).ready(function () {
var output[];
$.get("phpfile.php")
.done(function(data) {
output = data;
});
});
output is now the array of all your results and can be used.
Related
this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe
I have a problem with google maps markers. I want to use polish characters in the names of the markers. As i have in my db. This is the file which i use to create proper (afaik) XML.
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect ('localhost', $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
$test = $row['name'];
//$test2 = string utf8_encode ( string $test );
echo 'name="' . $test . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'city="' . $row['city'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
I get proper output from my db using this file (browser display polish characters properly) but when i create a map using:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBdj-LlQrTCj6bQcAq4fxONy9MaZcXvfc8"
type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50.046465, 19.913828),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("markergen.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("city");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map"></div>
</body>
</html>
Then i get whole data, but without correctly displayed polish characters.
I know that i should probably use
string utf8_encode ( string $data )
but i did try to put it in first file to convert data and fail.
So my question is where i should put it exactly into my code? Or is there any other/better option to do this.
EDIT:
I'm now trying to use DOM objects like this:
<?php
require("../test1/phpsqlinfo_dbinfo.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$mysqli = new mysqli("localhost", $username, $password, $database);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = $mysqli->query($query);
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("city", $row['city']);
}
echo $dom->saveXML();
?>
But now i have marker inside of marker in results like: <marker><marker>...</marker></marker> with data ofc. How to fix it? Still i'm not sure that data are correctly encoded but should be.
No, you should not use utf8_encode().
You should however use ext/mysqli or ext/pdo (not the old, depreacted and removed ext/mysql). Set the connection encoding to UTF-8 to get all strings as UTF-8 from the database.
Then use an XML library (DOM or XMLWriter) to generate the XML output. The libraries will encode/escape special characters as needed.
It will provide the missing XML declaration, too.
I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
my php code get_marker_connect2.php
<?php
$servername = "localhost";
$username = "root";
$passcode = "";
$dbname = "complaint_system";
$con=mysqli_connect($servername,$username,$passcode,$dbname);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//store query
$result = mysqli_query($con,"SELECT l_longitude,l_latitude FROM register_complain");
echo "<table border='1'>
<tr>
<th>Latitude</th>
<th>Longitude</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['l_longitude'] . "</td>";
echo "<td>
" . $row['l_latitude'] . "</td>";
echo "</tr>";
}
echo "</table>";
header('Location:http://localhost/cca/View_Map.html');
mysqli_close($con);
?>
This is my javascript named as javascript1.js
function initialize() {
var myLatLng = new google.maps.LatLng(24.86, 67.01);
var mapOptions = {
center: myLatLng,
zoom: 14,
mapTypeControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP};
alert('alert array here');
/*for (var i = 0; i < latlong1.length; i++) {
alert(" Longitude = ". latlong1[i].longitude);
alert(" Latitude = ". latlong1[i].latitude);
}
*/
map = new google.maps.Map(document.getElementById("view-map"),
mapOptions);
var marker = new google.maps.Marker({
position: simple,
map: map,
title: 'Hello Karachi!'});
}
google.maps.event.addDomListener(window, 'load', initialize);
can i move php array $row['l_longitude'] and $row['l_latitude'] directly to my javascript? i have google it alot but have not found solution yet.
i want to alert that array in my javascript at "alert array here"
If you wish to print a complex structure into your page that is worked in a browser, you need a syntax that Javascript can parse, and the serverside language can print.
The neareset possibilities are:
XML
JSON
I recommend JSON for now.
So with PHP, you write somewhere:
echo "var myTransportedArrayJson = \"" . json_encode($my_array) . "\"";
And then let the Javascript parse your json expression:
var myTransportedArray = JSON.parse(myTransportedArrayJson);
alert(myTransportedArray); // <<< and here you are.
Of course the snippet must be part of the response, otherwise it won't reach the server. Also, you should embrace the parsing with try .. catch. If you go on and work with even more complex structures, you have to consider escaping certain chars. So you will find now some literature :-)
I'm retrieving a string of LatLng coordinates from a database and used PHP's explode function and stored it in an array. I want to pass the array from PHP to JavaScript. Also, I want the Polygon function to accept the array and draw the coordinates accordingly. I'm currently stumped. :( Please help.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzZfro&sensor=false">
</script>
<script>
function initialize() {
var myLatLng = new google.maps.LatLng(8.5000,125.8333);
var myOptions = {
zoom: 8,
center: myLatLng,
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
var davaoCoordinates = [
new google.maps.LatLng(7.0644,125.6078),
new google.maps.LatLng(8.4833,124.6500),
new google.maps.LatLng(8.5000,125.8333)
];
var davaoCity = new google.maps.Polygon({
path: davaoCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
davaoCity.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the PHP code:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db('capdb');
if (mysqli_connect_errno()){
echo "Failed to connect to database: " . mysqli_connect_error();
}
$query ="SELECT cap_info.event, cap_info.sendername, cap_info.urgency, cap_area.polygon
FROM cap_info
INNER JOIN cap_area ON cap_info.capid = cap_area.capid
WHERE cap_info.capid =1";
$result = mysql_query($query);
if (!$result){
echo "Query Error." . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0){
echo "No rows found, nothing to print.";
exit;
}
while ($row = mysql_fetch_array($result)){
$event = $row['event'];
$sender = $row['sendername'];
$urgency = $row['urgency'];
$polygon = $row['polygon']."\n";
}
$coordsArray = explode (" ", $polygon);
$count = sizeof($coordsArray);
//$n=0;
//while ($n < $count){
//echo $coordsArray[$n];
//$n++;
//}
?>
Not sure what your array looks like, but, In your php, just create the points for the poly with something like below. That should at least help point you in the right direction.
$poly = "";
// loop all values
foreach($array as $v) {
$poly .= "new google.maps.LatLng(".$v."),\n";
}
// add first item from array to close poly
$poly .= "new google.maps.LatLng(".$array[0].")";
Then, in your javascript, just echo the values where you need them
var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
var davaoCoordinates = [
<?php echo $poly; ?>
];