javascript - How to fetch correct data from database with ajax -


in project, use ajax fetch data db. , test data content, choose alert(valdata) in success function. unlucky, nothing return ajax. tested

select contact idc id=5; 

it works fine in mysql cmd line.

here js code:

var stnum = 5; $.ajax({         datatype:'json',         type:"post",         url:"get_ajax_csc.php",         data:{stnum:stnum},         success:function(data)          {          var valdata = data;          alert(valdata);         }       }); 

here get_ajax_csc.php code:

<?php if(isset($_post['stnum'])) {     include("db.php");   $q=$_post["stnum"];  $sql="select contact idc id='".$q."';";  $sel = $conn->query($sql);    $arr = $sel->fetch(pdo::fetch_assoc);  echo $arr['contact'];  }  if(isset($_post['htmlcnt'])) {    include("db.php"); $htcnt=stripslashes(".$_post['htmlcnt']."); ........  }  ?> 

here db.php code:

<?php session_start(); $pwd=$_session['password']; $user=$_session['user'];  try  {   $conn = new pdo('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd); } catch (pdoexception $e) {   echo "account or pwd wrong <meta http-equiv='refresh' content='1;url=index.html'>";     exit; }   $conn->setattribute(pdo::attr_oracle_nulls, true); ?> 

it seems nothing wrong in code, cann't fetch data db

i have no idea error, can me ?

the data send server client not valid json data have specify in ajax expecting json data.

also queries not same :

select contact idc id=5; // correct query run on cmd line.    $sql="select contact idc id='".$q."';"; // 1 php 

if take close @ queries first 1 id treated integer on second 1 string. see when use single quotes, double quotes, , backticks in mysql

also using pdo take advantage of using prepared statements. try below code:

<?php if (isset($_post['stnum'])) {     include("db.php");      $q   = $_post["stnum"];     $sql = "select contact idc id= ? ";      $sel = $conn->prepare($sql);     $sel->bindparam(1, $q, pdo::param_int);     $sel->execute();     $arr = $sel->fetchcolumn(pdo::fetch_assoc);     echo json_encode($arr['contact']); //send json data client } ?> 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -