数据从javascript代码插入到mysql数据库

Data from javascript code insert to mysql database

本文关键字:mysql 数据库 插入 代码 javascript 数据      更新时间:2023-09-26

在这里,我有一个脚本可以帮助我从谷歌地点API获取地点。所以现在我想将所有这些存储到 mysql 中,但是如何存储?我是 mysql 和 php 的新手,如何将我从谷歌地方获得的数据存储到数据库?

我需要在这里做什么?有人可以给我举个例子吗...

如何结合php和javascript;

代码:http://jsbin.com/AlEVaCa/1

所以我需要存储我从谷歌获得的数据:

google.maps.event.addListener(marker,'click',function(){
        service.getDetails(request, function(place, status) {
          if (status == google.maps.places.PlacesServiceStatus.OK) {
            var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
            if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
            if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
            contentStr += '<br>'+place.types+'</p>';
            infowindow.setContent(contentStr);
            infowindow.open(map,marker);
          } else { 
            var contentStr = "<h5>No Result, status="+status+"</h5>";
            infowindow.setContent(contentStr);
            infowindow.open(map,marker);
          }
        });
    });

我想存储所有的地方名称,网站...等数据到我的数据库。怎么做?有没有办法存储这些数据?

使用 AJAX 将数据发送到 PHP 文件。

使用 jQuery $.post()-AJAX 方法将数据发送到 php 文件

 data = "name="+name+"&place="+website;
 $.post('file_to_store.php', data, function(data) {
     //Here you can get the output from PHP file which is (data) here
 });

纯JavaScript方式

function loadXMLDoc()
{
   var xmlhttp;
   if (window.XMLHttpRequest){
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
   }
   else{
      // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange=function(){
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
     }
   }
   data = "name="+name+"&place="+website;
   xmlhttp.open("POST","file_to_store.php",true);
   xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
   xmlhttp.send(data);
}

在file_to_store.php接收来自 $_POST[] 全局数组的所有数据

 if(isset($_POST)){
   $name = $_POST['name'];
   $website = $_POST['website'];
   //Do same for all other variables
   //Steps to insert Data into Database
   //1. Connect to database 
   //2. Select Database
   //3. Generate Database Insert Query
   //4. Run mysql Query to insert
   // Return appropriate return back to Javascript code - Success or Failure 
 }
使用

serialize($data) 然后将其放入数据库,从 db 获取数据后使用 unserialize()

另外:这将存储原始数据,您可能还需要一个解析器。

补充 2:对不起,我假设你得到了一个数组。

如果您获得非阵列数据,则替代解决方案:可以使用base64_encode($raw_data)来存储,base64_decode($encoded_data)使用来自 SQL 的编码数据。

从根本上说,在客户端执行的 JavaScript 程序无法直接访问主机上的 SQL 数据库 必须使用 AJAX 向主机发出请求,并且必须对主机端软件进行编程以处理这些请求。 很多(!关于这个主题的现有教程已经在那里......到处。