I'm trying to get information from my local ontology on GraphDB with a PHP script.
Online I've only found this this, so I've tried to adapt it to my necessities.
// ARC2 static class inclusion
include_once('semsol/ARC2.php');
$dbpconfig = array(
"remote_store_endpoint" => "http://localhost:7200/sparql",
);
$store = ARC2::getRemoteStore($dbpconfig);
if ($errs = $store->getErrors()) {
echo "<h1>getRemoteSotre error<h1>" ;
};
$query = 'PREFIX aplm: <http://www.andareperlomondo.it/rdf/ontologia.rdf#>
select * where {
?s aplm:nomeCognome ?o .
}';
// execute the query
$rows = $store->query($query, 'rows');
if ($errs = $store->getErrors()) {
echo "Query errors\n" ;
print_r($errs);
};
// display the results in an HTML table
foreach ($rows as $value) {
echo $value;
};
However, the connection doesn't work and in PHP prints the following error:
Array (
[0] => 404 "Not Found (HTTP status 404)..." in ARC2_Reader
[1] => missing stream in "getFormat" via ARC2_Reader
[2] => missing stream in "readStream" http://localhost:7200/sparql?query=%0APREFIX+aplm%3A+%3Chttp%3A%2F%2Fwww.andareperlomondo.it%2Frdf%2Fontologia.rdf%23%3E%0A%09%09%09%09%09%09%09%09select+%2A+where+%7B+%0A%09%09%09%09%09%09%09%09%09%3Fs+aplm%3AnomeCognome+%3Fo+.%0A%09%09%09%09%09%09%09%09%7D via ARC2_Reader
)
What shuld I do?
Related
I'm trying to send an array of data from PHP to ajax. I'm using echo json_encode to do it. When I do that, I try 'console.log(data)' to see the response data but it not show anything. How can I get it to display the data? I really don't know what I'm missing here. I have this script:
var scard = $('#cardid').val();
$.ajax({
type: 'GET',
url: 'cardapi.php?scard=' + scard,
success: function (data) {
console.log($.parseJSON(data));
console.log(data);
}
});
And here is my code for cardapi.php
if(isset($_GET["scard"])){
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no='$scard'";
$q = sqlsrv_query($conn, $sql);
while($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)){
array_push($data,[
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1,
]);
}
echo json_encode($data);
}
So I try to follow this echo json_encode() not working via ajax call
It still not show anything. Please tell me why?
Thank you.
You may try the following:
Always check the result from the sqlsrv_query() execution.
Always try to use parameterized statements. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Check the result from the json_encode() call.
Fix the typing errors ("signed_status" => 1, should be "signed_status" => 1 for example).
Sample script, based on your code:
<?php
if (isset($_GET["scard"])) {
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no = ?";
$params = array($scard);
$q = sqlsrv_query($conn, $sql, $params);
if ($q === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)) {
$data[] = array(
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1
);
}
$json = json_encode($data);
if ($json === false) {
echo json_last_error_msg();
exit;
}
echo $json;
}
?>
I usually work with web hosting companies but I decided to start learning working with servers to expand my knowledge.
I'll better give a real example to explain my question the best:
I have a web application that gathers data from a slow API that returns JSON data of products.
I have a function running every 1AM running a lot of queries on "id"s in my database.
Crontab:
0 1 * * * cd /var/www/html/tools; php index.php aso Cli_kas kas_alert
So this creates a process for the app (please correct me here if I'm wrong) and each process creates threads, and just to be more accurate, they are multi-threads since they do more than one thing: like pulling data from the DB to get the right variables and string them to the API queries, getting the data from the API, organizing it, searching the relevant data, and then inserting new data to the database.
The main PHP functions:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
For #Raptor, this is the function that get's the API data:
// aaa tag Query
// Gets aaa prod dataing by ID.
public function get_data_aaa_by_id_and_tg($id, $tag, $query_country){
$tag_for_url = rawurlencode($tag);
$found = FALSE;
$i = 0;
$data = array();
// Create a stream for Json. That's how the code knows what to expect to get.
$context_opts = array(
'http' => array(
'method' => "GET",
'header' => "Accepts: application/json\r\n"
));
$context = stream_context_create($context_opts);
while ($found == FALSE) {
// aaa Query
$json_query_aaa = "https://api.example.com:443/aaa/ajax/research_tag?app_id=$id&term=$tag_for_url&page_index=$i&country=$query_country&auth_token=666";
// Get the Json
$json_query_aaa = file_get_contents($json_query_aaa, false, $context);
// Turn Json to a PHP array
$json_query_aaa = json_decode($json_query_aaa, true);
// Get the data2
$data2 = $json_query_aaa['tag']['data2'];
if (is_null($data2)){ $data2 = 0; }
// Get data3
$data3 = $json_query_aaa['tag']['phone_prod']['data3'];
if (is_null($data3)){ $data3 = 0; }
// Finally, the main prod array.
$json_query_aaa = $json_query_aaa['tag']['phone_prod']['app_list'];
if ( count($json_query_aaa) > 2 ) {
for ( $j=0; $j<count($json_query_aaa); $j++ ) {
if ( $json_query_aaa[$j]['id'] == $id ) {
$found = TRUE;
$data = $json_query_aaa[$j]['data'] + 1;
break;
}
if ($found == TRUE){
break;
}
}
$i++;
} else {
$data = 0;
break;
}
}
$data['data1'] = $data;
$data['data2'] = $data2;
$data['data3'] = $data3;
return $data;
}
All threads are stacked one after an other, and when one thread is done, only then - the second thread can proceed, ect'.
And in technical view on this, all threads wait in the RAM until the one before them is done working "inside" the CPU. (correct me if I'm wrong again :] )
This doesn't even "tickle" the servers RAM or CPU when looking at it in the process manager (I use "htop"). RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%.
Making me feel this isn't the best I can get from my current server, and getting slow results from my web app.
How do I get things done in a way that all threads work in parallel, but not to a point that my app crashes due to lacks of CPU or RAM?
Currently working with a php project in which I connect to a database in phpmyadmin. I'm currently implementing my one to many relationship and on one of my forms there is a drop down list with the list of categorys(foreign key) that a product in my database can have, however when I check the post array, and the array that contains all the values for the insert query everything is there except the foreign key.
Drop down list and array of values:
<select name="Category_ID">
<?php
foreach ($category as $cat) {
echo '<option value="' . $cat['ID'] . '">' . $cat['ID'] . '</option>';
}
?>
</select>
Array (
[authorName] => Hiroshi Sakurazaka
[bookName] => All You Need Is Kill
[costPrice] => 59
[sellPrice] => 99
[productCatID] => )
Could not insert book
Heres the file that converts the data in the formdata array into an object:
<?php
require_once 'product.php'; //Connecting to the product class
require_once 'Classes/productTable.php'; //Connecting to the TableGateway
require_once 'Classes/Connection.php'; //Connecting to the Connection class
require_once 'validateProduct.php';//Connecting to the product validation
require_once 'utils/functions.php';
//start_session();
//
//if (!is_logged_in()) {
// header("Location: login_form.php");
//}
echo '<pre>';
print_r($_POST);
echo '</pre>';
$formdata = array();
$errors = array();
validate($formdata, $errors);
if (empty($errors)) {
$AuthorName = $formdata['AuthorName'];
$BookName = $formdata['BookName'];
$costPrice = $formdata['CostPrice'];
$sellPrice = $formdata['sellPrice'];
$productCatID = $formdata['productCatID'];
echo '<pre>';
print_r($formdata);
echo 'Form Data array';
echo '</pre>';
$connection = Connection::getInstance();
$gateway = new productTable($connection);
$id = $gateway->insert($AuthorName, $BookName, $costPrice, $sellPrice, $productCatID);
header('Location: viewProducts.php');
}
else {
require 'createProductForm.php';
}
Heres the function in the table gateway that inserts the object into the database:
> public function insert($authorName, $bookName, $costPrice, $sellPrice,
> $productCatID) {
> $sql = "INSERT INTO "
> . "`product`(`AuthorName`, `BookName`, `CostPrice`, `sellPrice`, `productCatID`)"
> . " VALUES (:authorName,:bookName,:costPrice,:sellPrice,:productCatID)";
> $statement = $this->connection->prepare($sql);
> $params = array(
> "authorName" => $authorName,
> "bookName" => $bookName,
> "costPrice" => $costPrice,
> "sellPrice" => $sellPrice,
> "productCatID" => $productCatID
> );
> print_r($params);
> $status = $statement->execute($params);
>
> if (!$status) {
> die("Could not insert book");
> }
>
> $id = $this->connection->lastInsertId();
>
> return $id; }
can somebody please tell me what I'm missing?
Your select has the name of Category_ID not productCatID. If you expecting GET/POST data coming in under productCatID you need to name your select productCatID.
Solved my problem finally, so I'll post how I did it. For debuging my code and to see what values were being passed into the $POST array and the $formdata array, I used print_r to post each array if there was a problem and heres what I got:
$POST Array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[productCatID] => 4
[createProduct] => Create Product
)
form data array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[ProductCatID] =>
)
As you can see the $POST array was getting the value from the drop down list just fine, it was the form data array that was the issue. Embarrassingly the issue was just a simple typo error that was quickly resolved in my validation script.
With foreach you have to explicitly request access to the key, so if you don't, you'll only get the array values.
Just do this to debug (outside of the <select>):
foreach($category as $key=>$cat){
var_dump($cat['ID'], $cat, $key);
}
And I think you'll see where the actual data you need is.
(also, you seem to be running without strict errors and notices on, which is crucial for debugging and might show you some notices when array keys you try to access don't exist)
<?php
include_once '../includes/db_connect.php';
fetch_evt_values($conn, 7475, 2, 16);
function fetch_evt_values($conn, $p_frm_id, $p_evt_id, $p_usr_id) {
$p_rec_id = 0;
$l_rslt_msg = '';
$l_result = array(
'data' => array(),
'msg' => '0000'
);
$sql = 'BEGIN PHPEVT.EV_MOD.FETCH_EVT_VALUES(';
//$sql .= ':c_load_id,';
$sql .= ':c_frm_id,';
$sql .= ':c_evt_id,';
$sql .= ':c_rec_id,';
$sql .= ':c_usr_id,';
$sql .= ':c_rslt';
$sql .= '); END;';
if ($stmt = oci_parse($conn,$sql)) {
$l_results = oci_new_cursor($conn);
//oci_bind_by_name($stmt,':c_load_id',$p_load_id);
oci_bind_by_name($stmt,':c_frm_id',$p_frm_id);
oci_bind_by_name($stmt,':c_evt_id',$p_evt_id);
oci_bind_by_name($stmt,':c_rec_id',$p_rec_id);
oci_bind_by_name($stmt,':c_usr_id',$p_usr_id);
oci_bind_by_name($stmt,':c_rslt',$l_results,-1,OCI_B_CURSOR);
if(oci_execute($stmt)){ //Execute the prepared query.
oci_execute($l_results);
while($r = oci_fetch_array($l_results,OCI_ASSOC)) {
$l_evt_values = explode('|', $r['EVENT_VALUES']);
foreach($l_evt_values as $l_evt_value) {
list($l_ID, $l_value) = explode('#', $l_evt_value);
$l_values[] = array('ID' => $l_ID, 'VALUE' => $l_value);
}
$l_result['data'][] = array(
'LOAD_ID' => $r['LOAD_ID'],
'REC_ID' => $r['REC_ID'],
'TRAIT' => $l_values,
'G_MSG' => $r['G_MSG']
);
$l_rslt_msg = $r['G_MSG'];
}
} else {
//echo 'cannot get user';
$l_rslt_msg = '0005'; //PHP_MEMBER.FETCH_USER return error code
}
} else {
//echo 'connect fail';
$l_rslt_msg = '0006'; //Could not connect to database.
}
oci_close($conn);
echo json_encode($l_result);
}
?>
So on a webpage, when a user requests an event, a database call is made using this code to retrieve some values in the format :
"62#20000|65#15710|66#6|67#6|68#0|69#0|".
The PHP then breaks it apart by |, splits the ID#Value, puts everything into an array, then returns it as a JSON which is then parsed into a table. The latter works perfectly fine. But when this tries to fetch more than about 600 records or so, I get a 500 Internal Server Error, and I've figured it's something in this PHP that's handling the call.
I'm not convinced it's the database entirely, as a call for 3500 records with no further processing other than the JSON being returned is generally done in 5s or less.
Why would this code be failing at 500+ records? I've tried AJAX timeout of 0.
Am a trying to create a PHP (PHrets) script that downloads all real estate listing information from a specific area and saves all of the listings data (CSV file and photos) on my web server.
Note: A single listing may have up to 20 photos.
I am using PHrets to retrieve MLS listing data and it works great for creating a CSV of data. However, I would like to modify this code to loop through each listing's photos and download them onto my web server with the following name convention: MLSID-PHOTOID.
The error below is coming from the GetObject loop at the end of the code:
ERROR Message: HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
Thanks in advance!
<?php
$rets_login_url = "http://maxebrdi.rets.fnismls.com/Rets/FNISRETS.aspx/MAXEBRDI/login?&rets-version=rets/1.5";
$rets_username = "MyUser";
$rets_password = "MyPass";
// use http://retsmd.com to help determine the SystemName of the DateTime field which
// designates when a record was last modified
$rets_status_field = "L_StatusCatID";
$rets_city_field = "L_City";
// use http://retsmd.com to help determine the names of the classes you want to pull.
// these might be something like RE_1, RES, RESI, 1, etc.
//"RE_1"
$property_classes = array("LR_5");
// DateTime which is used to determine how far back to retrieve records.
// using a really old date so we can get everything
$listing_status = 1;
$listing_city = "OAKLAND";
//////////////////////////////
require_once("phrets.php");
// start rets connection
$rets = new phRETS;
echo "+ Connecting to {$rets_login_url} as {$rets_username}<br>\n";
$connect = $rets->Connect($rets_login_url, $rets_username, $rets_password);
if ($connect) {
echo " + Connected<br>\n";
}
else {
echo " + Not connected:<br>\n";
print_r($rets->Error());
exit;
}
foreach ($property_classes as $class) {
echo "+ Property:{$class}<br>\n";
$file_name = strtolower("property_{$class}.csv");
$fh = fopen($file_name, "w+");
$maxrows = true;
$offset = 1;
$limit = 1000;
$fields_order = array();
while ($maxrows) {
$query = "({$rets_status_field}={$listing_status}),({$rets_city_field}={$listing_city})";
// run RETS search
echo " + Query: {$query} Limit: {$limit} Offset: {$offset}<br>\n";
$search = $rets->SearchQuery("Property", $class, $query, array("Limit" => $limit, "Offset" => $offset, "Format" => "COMPACT", "Select" => "L_ListingID,L_Class,L_Type_,L_Status,L_AskingPrice,L_Keyword2,L_Keyword3,L_Keyword4,L_SquareFeet,L_Remarks,L_Address,L_City,L_State,LO1_OrganizationName,LA1_AgentLicenseID,LA1_UserFirstName,LA1_UserLastName,L_PictureCount", "Count" => 1));
if ($rets->NumRows() > 0) {
if ($offset == 1) {
// print filename headers as first line
$fields_order = $rets->SearchGetFields($search);
fputcsv($fh, $fields_order);
}
// process results
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
$offset = ($offset + $rets->NumRows());
}
$maxrows = $rets->IsMaxrowsReached();
echo " + Total found: {$rets->TotalRecordsFound()}<br>\n";
$rets->FreeResult($search);
}
fclose($fh);
echo " - done<br>\n";
}
/*
//This code needs to be fixed. Not sure how to include the listing array correctly.
$photos = $rets->GetObject("Property", "Photo", $record[ListingID], "*", 1);
foreach ($photos as $photo) {
$listing = $photo['Content-ID'];
$number = $photo['Object-ID'];
if ($photo['Success'] == true) {
echo "{$listing}'s #{$number} photo is at {$photo['Location']}\n";
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg",
$photo['Data']);
}
else {
echo "Error ({$photo['Content-ID']}-{$photo['Object-ID']}
}
}
//ERROR Message: HTTP Error 500 (Internal Server Error): An unexpected condition was //encountered while the server was attempting to fulfill the request.
*/
echo "+ Disconnecting<br>\n";
$rets->Disconnect();
I modified your while loop that processes each record to also get the photos for that record. I also tested this on a RETS server.
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
if ($fo == 'L_ListingID') {
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
foreach ($photos as $photo) {
if ($photo['Success'] == true) {
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg", $photo['Data']);
}
}
}
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
One thing I found is you have ListingID on this line:
$photos = $rets->GetObject("Property", "Photo", $record[ListingID], "*", 1);
But then in your search query you refer to ListingID as L_ListingID. Maybe the above line should have L_ListingID.
$search = $rets->SearchQuery("Property", $class, $query, array("Limit" => $limit, "Offset" => $offset, "Format" => "COMPACT", "Select" => "L_ListingID,L_Class,L_Type_,L_Status,L_AskingPrice,L_Keyword2,L_Keyword3,L_Keyword4,L_SquareFeet,L_Remarks,L_Address,L_City,L_State,LO1_OrganizationName,LA1_AgentLicenseID,LA1_UserFirstName,LA1_UserLastName,L_PictureCount", "Count" => 1));
What if the last parameter of GetObject is "0" :
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
in this case "1" is for retreiving the location. some servers this is switched off and return the actual image I believe - that would require a different method.