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.
Related
Try to adopt JSON in database because i have data not fixed.
i can query well from terminal, and need to write same query to php script.
i have spent a lot of time before ask.
example:
sqlite> select json_extract(events.interni, '$') from events WHERE id='35';
output
[{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
where id = 35 will become a variable of $ _POST ['id']
what I tried:
$result2 = $db->query("select json_extract(events.interni, '$') from events WHERE id='35'");
var_dump($result2->fetchAll(PDO::FETCH_ASSOC));
return [] <- empty array
i want instead = [{"student_id":"21","student_name":"Rafael Royal"}]
where did I go wrong?
I followed this answer on SO https://stackoverflow.com/a/33433552/1273715
but i need to move the query in php for an ajax call
possibile another help.
Can the result fron $ajax call can be usable as key value or remain string?
in other hands i can convert string to object like students = new Object()?
eaxaple of what i need in js environment
- count objects in array
- and loop key value
var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));
here I would like to avoid the backslash
consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2
any possible help is largely appreciated
UPDATE
leave json_extract() function i have solved the second problem, so now i can work whit object property, and finally important to count objects in array:
<?php
try {
$db = new PDO('sqlite:eventi.sqlite3');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
echo $e->getMessage();
}
$risultato = $db->query("SELECT * FROM events WHERE id = '35'", PDO::FETCH_ASSOC);
$result = array();
foreach ($risultato as $row) {
$result[] = $row;
}
// echo "Results: ", json_encode($result), "\n"; this produced backslash
echo $result[0]['interni'];
?>
js part
var num='';
$.ajax({
url: "sqlitedb/test-con.php",
type: 'POST',
dataType: 'json',
success:function(result){
console.log(result[0].student_id+ " - "+ result[0].student_name); // output here is good: 12 - Lisa Ochoa
counter(Object.keys(result).length);
}});
function counter (numero){
console.log("num2: =" + numero);
}
//out put here: 2
perfect!
odd behaviour:
console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa
outup is right but
console.log(result.lenght);
output is null
You can try something like this. and since you said in the comment about approaching it with ajax. I have included that also.
I also include php mysql backend workability for clarity. so Yo have now two options
1.) PHP WITH MYSQL
2.) PHP WITH SQLITE as you requested
index.html
<script src="jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'data.php',
dataType: 'JSON',
cache:false,
success: function(data){
var length = data.length;
for(var s=0; s<length; s++){
var student_id = data[s].student_id;
var student_name = data[s].student_name;
var res = "<div>" +
"<b>student_id:</b> " + student_id + "<br>" +
"<b>student_name:</b> " + student_name + "<br>" +
"</div><br>";
$("#Result").append(res);
}
}
});
});
</script>
<body>
<div id="Result" ></div>
</body>
In mysql database you can do it this way.
<?php
$host = "localhost";
$user = "ryour username";
$password = "your password";
$dbname = "your bd name";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}
$return_arr = array();
$query = "SELECT id, student_id, student_name FROM events where id='35'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
?>
So with sqlitedb something like this will work for you
$return_arr = array();
$result2 = $db->query("SELECT id, student_id, student_name FROM events where id='35'");
$result2->execute(array());
//$result2 = $db->query("SELECT * FROM events where id='35'");
//$result =$result2->fetchAll(PDO::FETCH_ASSOC));
while($row = $result2->fetch()){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
You are surrounding you query with double quotes but inside the query there is an unescaped $.
Try escaping it:
$result2 = $db->query("SELECT json_extract(events.interni, '\$') FROM events WHERE id='35'");
var_export($result2->fetchAll(PDO::FETCH_ASSOC));
autocomplete bootstrap php mysql ajax
autocomplete bootstrap php mysql from databse
data not fetching from database not showing suggestion
my code not showing any result please help to complete my code
i have change many time my code
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP
Search Country
// script
$(document).ready(function(){
$('#country').typeahead({
source: function(query, result)
{
$.ajax({
url:"autoselect_jquery5.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
// autoselect_jquery5.php
<?php
include 'database.php';
if (isset($_POST['query'])) {
// $search_query = $_POST['query'];
$search_query = mysqli_real_escape_string( $_POST["query"]);
$query = "SELECT * FROM transporter WHERE address LIKE '%".$search_query."%' LIMIT 12";
// $query = "SELECT * FROM transporter WHERE address LIKE %'
$search_query ' LIMIT 12";
$result = mysqli_query($link, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["address"];
}
echo json_encode($data);
}
}
?>
You have multiple errors in your file. I have commented this up fully to help others who come across this question.
<?php
//Assume this line is correct and that you have a database.php file containing your log in credientials
include 'database.php';
//If Statement says - run this next piece of code if $_POST['query'] is set to something
if (isset($_POST['query']))
{
// $search_query = $_POST['query']; - Commented OUT
//This line attempts to sanatise the input from the posted data
$search_query = mysqli_real_escape_string( $_POST["query"]);
//This line constructs the whole SQL statement ( BAd methodology here, but thats a different topic)
$query = "SELECT * FROM transporter WHERE address LIKE '%".$search_query."%' LIMIT 12";
//You've commented out the next line and its of no use
// $query = "SELECT * FROM transporter WHERE address LIKE %'
//This line has a syntax error - but is also of no use - Should delete but should read $search_query = ' LIMIT 12';
//$search_query ' LIMIT 12";
/// This line queries the database
$result = mysqli_query($link, $query);
//This line declares $data will be an array
$data = array();
//If the DB returns some rows
if(mysqli_num_rows($result) > 0)
{
// While there are results
while($row = mysqli_fetch_assoc($result))
{
//add to the $data array
$data[] = $row["address"];
}
//Output $data in JSON format to be interpreted as a response from your ajax call
echo json_encode($data);
}
}
?>
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.
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']);
Background:
I have a page which dynamically pulls up a modal window, which displays extended information on a row (with multiple columns) through mySQL. I am having issues where my JSON code will not populate the information correctly so that it can be outputted. I have tried multiple nested arrays, while loops and for loops. However, I only need to return one full row of information from the database. After scratching my head, I am asking the help of all the SO experts. Any pointers are much appreciated.
Ajax Code For Div Population (Works)
var data_id = $(this).data('id');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: {id: data_id},
dataType: 'json',
success: function(data){
$('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
},
error: function(jqXHR, textStatus, errorThrown){
$('.view_modal_content').html(''); // LOAD THE DATA INTO THIS DIV
alert('Error Loading Information');
}
});
JSON Code To Pull Information and return HTML
<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]=$row['agency_name'];
$message[]=$row['account_number'];
$message[]=$row['phone'];
}
$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
header('Content-Type: application/json');
echo json_encode( $json );
?>
Additional Question:
Is it possible to reference the headers in the array using " $message['agency_name'] "inside the html that gets returned?
After solving this problem, I will need to turn the outputted html into a structure to allow my users to view the information in a properly understandable format. I know how to do this in html, but I am unfamiliar with JSON... Is there a way to output the information without having to manually code the structure?
Thank you in advance.
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(db_nname", $con);
$result = mysql_query("SELECT phone,agency_name FROM '''' ");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['results'][] = $r;
}
print json_encode($rows);
?>
and in your html
<table id ="listtable"></table>
var listdiv = $("#listtable");
$.getJSON("whatever.php",function(json){
$.each(json.results,function(i,data){
listdiv.append("<tr><th>" + data.phone + "</th><th>" + data.agency_name + "</th></tr>");
});
});
and in the append use data. and whatever your fields are
data.agency_name
data.phone
etc....