Calling JSON data through the function inside the php? - php

Actually , I did the JSON calling from the PHP file named as student_detail.php
localhost/demo/student_details.php
I need to call the JSON file inside the student_details.php file. like
localhost/demo/student_details/get_Students_Details
by calling this way it shows an error like object not found. Here my code
<?php
include('database.php');
class student_details
{
public function get_Students_Data()
{
$query = "select * from student_table";
$result = mysql_query($query);
$student_data = array();
while($row = mysql_fetch_assoc($result))
{
$student_data[] = array(
'Student Id' => $row["student_id"],
'Register No' => $row["student_register_no"],
'Roll No' => $row["student_roll_no"],
'Name' => $row["student_name"],
'Date Of Birth' => $row["student_DOB"],
'Gender' => $row["student_gender"],
'Nationality' => $row["student_nationality"],
'City' => $row["student_city"],
'Pincode' => $row["student_pincode"]
);
};
echo json_encode($student_data,JSON_PRETTY_PRINT);
}
}
?>
How do I resolve it.?

You are using "clean urls", which pure PHP doesnt support.
Its unclear if you are using a framework which does support that or not.
Your code, as is, should work if you are using a framework with clean urls.
Please provide some more informations for further help.
If you do NOT use a framework, all you have to do is create a new file, which will be called if you want to request a JSON response. Then you create a new object of your student_details class and call the method get_Student_Data().
i.e:
<?php
include('classes/student_details.php');
$student = new student_details;
$student->get_Student_Data();
Unrelated, but still important: do NOT use mysql_* functions, since they are deprecated in PHP 5.5 and removed from PHP 7. Use mysqli_* or PDO instead.

Related

CakePHP 3 autocomplete AJAX responses

I have been trying to get cakephp to suggest input from data that is from my tables like autocomplete. I've done some reading about how some other people have done this but still can't figure it out. Currently it seems that every time my controller is waiting for an ajax request and it is always false. No errors come up from the console some i'm not sure what i'm doing wrong. I tried removing the if ($this->request->is('ajax')) statement but then I get a error about it cannot emit headers.
Here is my search function in InvoicesController which I have taken code from someone else example but failed to implement it.
public function search()
{
if ($this->request->is('ajax')) {
$this->autoRender = false;
pr('b');
$name = $this->request->query['term'];
$results = $this->Invoices->find('all', [
'conditions' => [ 'OR' => [
'id LIKE' => $id . '%',
]]
]);
$resultsArr = [];
foreach ($results as $result) {
$resultsArr[] =['label' => $result['full_name'], 'value' => $result['id']];
}
echo json_encode($resultsArr);
}
}
And here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']);?>
<script>
jQuery('#id').autocomplete({
source:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>',
minLength: 1
});
</script>
This is my invoice table and the ids are what I want to be suggested from what users type in.
I may not be seeing your exact problem but let me point out a few things I see that might help this issue.
Remove this line. It is not necessary
$this->autoRender = false;
Instead you should be doing this at the end. See using the RequestHandler
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', 'resultsArr');
This will return the data without a root key
[
{"label":"Label Value"},
{"label":"Another Label Value"}
]
Or you can do it like this
$this->set('_serialize', ['resultsArr']);
This will return data like
{"resultArr":[
{"label":"Label Value"},
{"label":"Another Value"}
]}
Replace your finder query with this.
$resultArr = $this->Invoices->find('all')
->where(['id LIKE' => $id . '%'])
// If you want to remap your data use map
// All queries are collections
->map(function ($invoice) {
return ['label' => $invoice->full_name, 'id' => $invoice->id];
});
It seems to me you might want to review the new cakephp 3 orm. A lot of hard work went into writing these docs so that they could be easily read and relevant. I'm not one to push docs on people but it will save you hours of frustration.
Cakephp 3 ORM documentation
A few minor things I noticed that are also problems.
You never define $id.
You define $name but never use it.
pr is a debug statement and I am not sure why you have it.
Based on your comment, here is an update on ajax detection.
// By default the ajax detection is limited to the x-request-with header
// I didn't want to have to set that for every ajax request
// So I overrode that with the accepts header.
// Any request where Accept is application/json the system will assume it is an ajax request
$this->request->addDetector('ajax', function ($request) {
$acceptHeaders = explode(',', $request->env('HTTP_ACCEPT'));
return in_array('application/json', $acceptHeaders);
});

MongoDB running command in lithium

I'm trying to run a full text search against some data that is stored in mongoDb using Lithium.
Here is how I am trying to do it in my controller:
$mongodb = Connections::get('default')->connection;
$results = Page::connection()->connection->command(array("text" => "Page", 'search' => "term" ));
I've also tried:
$results = Page::connection()->connection->command(array("text" => "Page", 'search' => "term" ));
However, both of these return: Fatal error: Call to a member function command() on a non-object
What am I doing wrong?
EDIT:
I should add that a simple query on Page is working just fine. For instance:
$results = Page::find('all');
Does return an array with all of the documents in the pages collection like I would expect it to.
UPDATE 2:
I was running all of this from WAMP server. I tried today running it from a linux server, but still got the same exact error. I am really stumped by this and could use some help. Anyone have any ideas?
here is the Page model as it sits now:
<?php
namespace app\models;
use lithium\data\Connections; //added during debugging
use lithium\data\source\MongoDb; //added during debuging
class Page extends \lithium\data\Model {
}
?>
Here is my connection:
Connections::add('default', array(
'type' => 'MongoDb',
'host' => '192.168.48.128',
'database' => 'my_collection'
));
I'm doing it this way:
$plugins = Plugins::connection()->connection->command([
'text' => 'plugins',
'search' => $this->request->query['q']
]);
return compact('plugins');
so I'd recommend checking your configuration - is your model returning other data normally? Is the connection configuration correct?
Got help to figure it out... posting here for others to reference.
proper way of calling it is:
$conn = Model::connection();
$db = $conn->selectDB('db');
$result = $db->command(array(...
Works perfectly when done this way.

CodeIgniter - Access database within a Helper

I have this code inside my view.
$country = array(
'id' => 'country',
'name' => 'country',
'value' => get_user_info('country'),
'size' => 30
);
<tr>
<td><?php echo form_label('Country', $country['id']); ?></td>
<td><?php echo form_input($country); ?></td>
<td style="color: red;"><?php echo form_error($country['name']); ?><?php echo isset($errors[$country['name']])?$errors[$country['name']]:''; ?></td>
</tr>
The get_user_info() is a function defined in my form_helper like this:
Form_Helper.php
if(! function_exists('get_user_info')){
function get_user_info($field)
{
$ci = & get_instance();
$ci->load->model('users');
return $ci->users->get_user_profile($field);
}
}
As you can see , inside this function I access the database through the users Model.
User_Model
function get_user_profile($field)
{
$user_id = $this->session->userdata('user_id');
$this->db->select($field);
$this->db->where('user_id',$user_id);
$query = $this->db->get($this->profile_table_name);
if($query->num_rows()==1)return $query->row();
return NULL;
}
The idea is to auto fill the Country field of the form while the page loads.
But in the view I am getting this error
A PHP Error was encountered
Severity: Warning
Message: htmlspecialchars() expects parameter 1 to be string, object given
Filename: helpers/form_helper.php
Line Number: 646
What can be the problem ?Can someone knows what is happening ? Or has someone did a such a thing in the past ?
Is it the right way to access the Model within a helper function ?
Thanks
EDIT
To do better and faster I simply call the model from my controller and then pass the different values to the view.
Controller
$d = $this->users->get_user_profile('country, telephone, city, street, address, town');
$d2 = Array(
'telephone' => $d->telephone,
'country' => $d->country,
'city' => $d->city,
'street' => $d->street,
'address' =>$d->address,
'town' => $d->town);
$this->template->write_view('contentw','dashboard/profile', $d2);
$this->template->render();
So I delete the function I added to my Helper file.
This method is working for me.
Thank you all for your answers
Generally helpers are used as Global functions to do some simple work. Most people would say it is wrong to invoke a Model in the middle of a helper. Helpers should be used like the PHP function explode; it has a single task, receives input, and provides output based on the input very mechanically.
It might be better instead for the controller to access the model and get that value, then pass it into the view and use it directly
As for the error:
You are probably getting that error because you are returning $query->row() instead of an actual value in that field. $query->row() is most likely an object and $query->row()->country is the actual value
Helpers aren't hooked into the rest of CI as far as I'm aware. I'm sure there's some way to get them to work like that, but maybe it would be more productive to just create a library?
If you create a library, you can have access to all the great stuff in CI through &=get_instance(); and it won't really be much different. You could make a Users library and call it like this:
$this->load->library('users');
$this->users->get_user_info('country');

CodeIgniter - Variable scope

I have a controller which I use for a login form. In the view, I have a {error} variable which I want to fill in by using the parser lib, when there is an error. I have a function index() in my controller, controlled by array $init which sets some base variables and the error message to '':
function index()
{
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$this->parser->parse('include/header', $init);
$this->parser->parse('login/index', $init);
$this->parser->parse('include/footer', $init);
}
At the end of my login script, I have the following:
if { // query successful }
else
{
$init['error'] = "fail";
$this->parser->parse('login/index', $init);
}
Now, of course this doesn't work. First of all, it only loads the index view, without header and footer, and it fails at setting the original $init['error'] to (in this case) "fail". I was trying to just call $this->index() with perhaps the array as argument, but I can't seem to figure out how I can pass a new $init['error'] which overrides the original one. Actually, while typing this, it seems to impossible to do what I want to do, as the original value will always override anything new.. since I declare it as nothing ('').
So, is there a way to get my error message in there, or not? And if so, how. If not, how would I go about getting my error message in the right spot? (my view: {error}. I've tried stuff with 'global' to bypass the variable scope but alas, this failed. Thanks a lot in advance.
$init musst be modified before generating your view.
To load your header and footer you can include the following command and the footer's equivalent into your view.
<?php $this->load->view('_header'); ?>
to display errors, you can as well use validation_errors()
if you are using the codeigniter form validation.
if you are using the datamapper orm for codeigniter you can write model validations, and if a query fails due to validation rule violation, you get a proper error message in the ->error property of your model.
Code for your model:
var $validation = array(
'user_name' => array(
'rules' => array('required', 'max_length' => 120),
'label' => 'Name'
)
);
You might try this:
function index() {
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$string = $this->parser->parse('include/header', $init, TRUE);
$string .= $this->parser->parse('login/index', $init, TRUE);
$string .= $this->parser->parse('include/footer', $init, TRUE);
$this->parser->parse_string(string);
}
In parse()you can pass TRUE (boolean) to the third parameter, when you want data returned instead of being sent (immediately) to the output class. By the other hand, the method parse_string works exactly like `parse(), only accepts a string as the first parameter in place of a view file, thus it works in conjunction.

JSON stub string delivered via php

I would like to make a web service stub where I can test my client. I have written down
some JSON like this:
{
"response": {
"success": true,
"meta" : "tags",
"data": [
{
"first_name" : "John",
"last_name" : "Doe",
"age" : 30
},
{
"first_name" : "Jane",
"last_name" : "Doe",
"age" : 25
}
]
}
}
I have no PHP experience to talk about.
How can I make a
webserver.com/get_names.php?first_name=john&last_name=doe&age=30
script that returns the above JSON.
It should not do any evaluation on the parameters, that is just how it will end up being called when implemented against a server, I would just like it to return the JSON string correctly so my JSON parser can run through it as if it was the actual server response.
Hope someone can help me out, thank you in advance.
Save the JSON string as-is and call the file get_names.php. Don't forget to pick UTF-8 in your editor's save as dialogue. Nothing will be parsed as PHP if there isn't a single <?php string in the file.
You may also want to put this on top of the file:
<?php
header('Content-Type: application/json');
?>
This is usually referred to as an API, and can be developed on many levels.
First level would be standard streamline php, where you would have code that follows the general php coding.
$Action = isset($_GET["action"]) ? $_GET["action"] : false;
switch($Action)
{
case 'get_names':
//fetch data and display.
break;
}
The next method and the simplest would be to use an MVC Application Framework, I would recommend Code Igniter for this as tis bigginner friendly and the URI Structure is similar to an API Soap Server.
After copying your CI Files to your /api/ path, you would go threw the guide and configure your database,libraries,helpers etc, you would also use mod_rewrite to set up the URI Convention to get urls such as /api/get/games/API_KEY
your class would look like so:
class Get extends Controller
{
public function __construct()
{
parent::Controller();
}
public function games($Api = false,$limit = 10, $offset = 0)
{
if(!$Api)
{
show_error("API Key require to fetch games");
}
if(your_api_check($api) === true)
{
//Load the games
$games = $this->models->games->get($limit,$offset);
$this->output->send(json_encode($games));
}
}
}
Obviously more extensive checking with the validation of the params but you will get the gist of it.
The next level would be very complex for your self but if you wish to persue the idea then you may want to look into Simple Object Access Protocol but ill leave that for you to decide.
Links:
Codeigniter
RESTful with Codeigniter
Restful with CodeIgniter #2
Codeigniter XMLRPC Services
You could save this as get_names.php on your web server.
<?php
$my_associative_array = array(
'response' => array(
'success' => true,
'meta' => 'tags',
'data' => array(
array(
'first_name' => 'John',
'last-name' => 'Doe',
'age' => 30,
),
array(
'first_name' => 'Jane',
'last_name' => 'Doe',
'age' => 25
),
),
),
);
echo json_encode($my_associative_array);
Alternatively, you could just create a .txt file that looks precisely like your JSON.
You could also just point it to my server, where the above script is operational: http://dorkitude.com/example_4725873.php

Categories