retrieve multiple data from various queries with ajax php mysql - php

I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>

If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.

Related

Buliding an API using php and json

I have the following scripts that displays database records via json. it works very fine.
My question is how do i create a secure API with it so that when users place the api say
http://www.waco.com/profile.php?id=0990999&security=xxxxxxxxx in their website,
it will pull the information from my server and display it on their site. below is the entire working code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
$(document).ready(function(){
var formhtml = "logreq=1";
var postURL= 'profile.php';
$.ajax({
type: "POST",
url: postURL,
data: formhtml,
dataType: JSON,
success: function(html){
var output= '<table class="logtable"><tbody><thead><th>Log</th><th>Username</th><th>Date</th><th>Event</th></thead>';
var logsData = $.parseJSON(html);
for (var i in logsData.logs){
output+="<tr><td>" + logsData.logs[i].title + "</td><td>" + logsData.logs[i].user + "</td><td>" + logsData.logs[i].date+ "</td><td>" + logsData.logs[i].log+"</td></tr>";
}
//write to container div
$("#log_container").html(output);
},
error: function (html) {
alert('Oops...Something went terribly wrong');
}
});
});
</script>
</head>
<body>
<div id="log_container">
</div>
</body>
</html>
<?php
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
?>
please i need help.
I am assuming that your example is an oversimplification, and that you will be looking into preventing SQL injections as well as any additional validation to ensure that you are getting the data you are expecting.
With that said, I would place your PHP code in a separate file for the user to call and drop your code into it like so:
if(isset($GET['id']) && isset($GET['security'])){
$id = $GET['id']; $secure = $GET['security']; // TODO: escape these strings
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20 Where id = $id And security = $secure";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
}
Hope that helps. This is good place to start. I would also look into PHP frameworks like CodeIgniter or Cake that will help you build your API properly.

POST variable from SELECT into sql query to output to an INPUT

Using Chain SELECT works great from SELECT to SELECT, I'm trying to do SELECT to INPUT.
My mainpage.php
<label>Manufacturer</label>
<select>My Select statement is here</select>
<label>Model</label>
<select name="modelname">My Select statement is fed from the select above</select>
<label>Rating</label>
<input name="rating"></input>
This is the jQuery I have in the <head> section on the mainpage.php
<script>
$(document).ready(function(){
$("select#modelname").change(function(){
var id = $("select#modelname option:selected").attr('value');
$.post("assets/configs/getdata.php", {id:id}, function(data){
$("input[name='rating']").html(data);
console.log(data);
});
});
});
</script>
and finally the getdata.php
<?php
include "db.php";
$modelid = $_POST[id];
$sql = "SELECT EfficiencyRating FROM AllModels WHERE ModelID = '$modelid' ";
$res = odbc_exec($cnn, $sql);
while ($row = odbc_fetch_array($res)) {
$row_array[] = $row['EfficiencyRating'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
Using the console log when this message is returned, how can I fix this?
HP Warning: array_push() expects parameter 1 to be array, null given in assets\configs\getdata.php on line 12
Try with this.
$res = odbc_exec($cnn, $sql);
$return_arr = array();
while ($row = odbc_fetch_array($res)) {
$return_arr[] = $row['EfficiencyRating'];
}
echo json_encode($return_arr);
JS Part
// Slightly modify the Request
$.post("assets/configs/getdata.php", {id:id}, function(data){
// JSON Object
console.log(data);
$("input[name='rating']").val(data);
}, 'json');
You need to declare $return_arr before the while statement. Also, I personally feel what you are doing is just not right. The proper way would be this...
$res = odbc_exec($cnn, $sql);
$return_arr = array(); //<----------- Here
while ($row = odbc_fetch_array($res)) {
array_push($return_arr,$row['EfficiencyRating']);
}
echo json_encode($return_arr);

Run php from jquery click, return array from php file which calls another file

yesterday i managed to get my data from a database outputting and storing to a java array. However that was on load, now that code wont work for on click.
So I have read about ajax and have this function:
var infArray = new Array();
var country;
$('#australia').click(function() {
//console.log("you clicked"+txt);
country = 'Australia';
$.ajax({
type: 'POST',
url: 'php/Maps.php',
data: {country: country},
success: function(data){
alert("success"+data); // this will hold your $result value
infArray = JSON.parse(data)
console.log( 'Return:' + data );
}
});
});
By my understanding this opens the php file containing the function and allows you to use the variable "country" by using $_POST.
So my php file looks like this :
<?php
require '../classes/Mysql.php';
function get_Stockist(){ // if su = 0 then stockist if = 1 then member
$mysql = new Mysql();
$result = $mysql->getInfo($_POST['country']);
echo json_encode($result);
}
so again in my eyes, $result is set to the result of the method :
in Mysql.php :
function getinfo($country){
$rows = array();
$query = "SELECT Name,add1 FROM stockistsWorld WHERE Country = '". mysql_escape_string($country) ."' LIMIT 5";
//$query = "SELECT Name,add1 FROM stockistsUK LIMIT 10";
$result = mysqli_query($this->conn, $query);
/* numeric array */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
$rows[] = $row;
}
return $rows;
}
However the result in my html is null
You never call your function get_Stockist() in your PHP file that gets called by AJAX.
Add get_Stockist() to your PHP file to call your function.
And your other function is getinfo, without capital i.
So it would be $mysql->getinfo($_POST['country']); instead of $mysql->getInfo($_POST['country']);

Get Data from Mysql instead XML?

hey i have this javascript for a bubble up... this script gets InfoID and InfoData tags from an xml file...
<script type="text/javascript">
$(document).ready( function ( ) {
// Get the XML data from your file
$.get('scores.xml', function( data ) {
// Because we've given jQuery the XML datatype, we can jump straight to finding the element.
$(data).find('Game').each( function ( ) {
// The current object now holds a single "GAME" - find the elements we need
var game_id = $(this).find('InfoID').text( );
var game_info = $(this).find('InfoData').text( );
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
}); // end of each
}, 'xml'); // The 'xml' tells jQuery to expect XML back from the request
});
</script>
i need to make this script get data from Database table instead of xml.
i have the same InfoID and InfoData rows in a table in my database...
i use this php script to get data from db:
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
<?php echo $row['Header'].""; ?>
<?php echo $row['Row'].""; ?>
<?php echo $row['Date'].""; ?>
<?php echo $row['Time'].""; ?>
<?php echo $row['AwayTeam'].""; ?>
<?php echo $row['Score'].""; ?>
<?php echo $row['HomeTeam'].""; ?>
<?php echo $row['Other'].""; ?>
<?php echo $row['InfoID'].""; ?>
<?php echo $row['InfoData'].""; ?>
<?php } mysql_close(); ?>
any idea how i can do that? so i can remove my xml file and use database :)
Thanks in advance.
You could use an ajax post with a seperate callback function and return json data from your php script.
Give this a shot:
// try this for your javascript
<script type="text/javascript">
$(document).ready( function ( ) {
function getGameInfo() {
$.post("path/to/phpScript.php",
// this is the success callback
function (json) {
// this calls the function with the returned data
parseReturnedData(json);
});
return false;
};
// process json data to set your game_id and game_info vars
function parseReturnedData(data) {
var obj = jQuery.parseJSON(data);
var game_id = obj.InfoID;
var game_info = obj.InfoData;
}
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
</script>
// try this for your php file
<?php
// declare vars
$response = array();
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
$response['Header'] = $Header;
$response['Row'] = $Row;
$response['Date'] = $Date;
$response['Time'] = $Time;
$response['AwayTeam'] = $AwayTeam;
$response['Score'] = $Score;
$response['HomeTeam'] = $HomeTeam;
$response['Other'] = $Other;
$response['InfoID'] = $InfoID;
$response['InfoData'] = $InfoData;
}
echo json_encode($response);
mysql_close();
?>

workout with the php returned array to jquery

my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });

Categories