php - Want to parse javascript variable to mysql database -
i have js file , js variable named mydata in array. want store component of mydata mysql dbase. tried using ajax (first of all, parse json file), still fail. i'm new in json , ajax. it's javascript. wrong?
var mydata = []; var arrayofmarker = []; function myfunctions(maps) { var count = 1; var arr = new array(); for(var i=0;i<mydata.length;i++){ var typef = ''; if (document.getelementbyid('optionsradios1').checked == true) { typef = 'building'; } else { typef = 'house'; } var ob = {0 : count, 1 : mydata[i][1], 2 : mydata[i][2], 3 : typef}; arr.push(ob); count += 1; } var myjstring = json.stringify(arr); console.log(myjstring); $.ajax({ url: 'inputdata.php', type:"post", datatype:'json', data: {data: myjstring}, cache: false, success: function(data){ console.log(data); }, error: function(request, status, error){} }); } </script>
and php file: inputdata.php
<?php $con = mysql_connect("root","","")or die('could not connect: '.mysql_error()); mysql_select_db("fpgis",$con); $data = json_decode($_post['data']); $sql = "insert pointproperty(nopoint,latpoint,lngpoint,tipepoint)values('$data[0]','$data[1]',' $data[2]','$data[3]')"; if(!mysql_query($sql,$con)){ die('error : '.mysql_error()); } ?>
please tell me how solve problem. need solution. solution helpful me. lot :)
you shouldn't use mysql_ in first place, use mysqli_ or pdo... bet you're using mysql_connect wrong... server hostname "root"? in http://root/ ? highly doubt it. see http://php.net/manual/en/function.mysql-connect.php correct usage (or better yet, http://wiki.hashphp.org/pdo_tutorial_for_mysql_developers ) ..but like
js:
var data={"foo":13,"bar":37}; var xhr=new xmlhttprequest(); xhr.open("post","sendtodb.php"); var fd=new formdata(); fd.append("data",json.stringify(data)); xhr.send(fd);
sendtodb.php:
<?php $data=json_decode($_post['data'],true,1337); //may want validate data content $db = new pdo('mysql:host=localhost;dbname=testdb;charset=utf8', 'root', 'password', array(pdo::attr_errmode => pdo::errmode_exception)); $pdos=$db->prepare("insert `fpgis` (`foo`,`bar`) values(?,?)"); $pdos->execute(array($data['foo'],$data['bar'])); unset($pdos);
....or if have use mysql_ reason,
<?php $con = mysql_connect("localhost","root","password")or die('could not connect: '.mysql_error()); mysql_select_db("fpgis",$con); $data = json_decode($_post['data']); $sql = "insert pointproperty(nopoint,latpoint,lngpoint,tipepoint)values('".mysql_real_escape_string($data['nopoint'],$con)."','".mysql_real_escape_string($data["latpoint"],$con)."','".mysql_real_escape_string($data["lngpoint"],$con).",'".mysql_real_escape_string($data["tipepoint"],$con)."')"; if(!mysql_query($sql,$con)){ die('error : '.mysql_error());
(if don't use mysql_real_escape_string, code unreliable when feeding objects properties or values containing special characters, , worse, you're opening website sql injection attacks, , you'll hacked :p)
Comments
Post a Comment