How to fetch SPARQL query result using EasyRdf - php

Using EasyRdf, I want to fetch query result. I used below code in codeigniter:
$this->load->library('rdf');
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl');
$sparql = new EasyRdf_Sparql_Client('http://localhost:3030/surat_single/sparql');
$query = "SELECT * WHERE { "
. "?surat rdf:type srt:Surat . "
. "?surat srt:sifat_surat ?sifat_surat . "
. "?surat srt:nomor_surat ?nomor_surat . }";
$result = $sparql->query($query);
echo "jumlah data: " . $result->numRows() . "<br>";
echo "<br>";
foreach ($result as $row) {
echo $row->sifat_surat . " " .$row->sifat_surat . " " . $row->nomor_surat ."<br>";
}
print_r($result);
The output I got are:
jumlah data: 0
EasyRdf_Sparql_Result Object (
[type:EasyRdf_Sparql_Result:private] => bindings
[boolean:EasyRdf_Sparql_Result:private] =>
[ordered:EasyRdf_Sparql_Result:private] =>
[distinct:EasyRdf_Sparql_Result:private] =>
[fields:EasyRdf_Sparql_Result:private] => Array (
[0] => surat
[1] => sifat_surat
[2] => nomor_surat
)
[storage:ArrayIterator:private] => Array ( )
)
I also try Joshua's solution given here, but got similar output. I also try my query in Fuseki endpoint (I'm using Fuseki triplestore) and got this result. I'm completely beginer in semantic web.

I don't know whether it's the answer or not, but these namespaces don't look right to me:
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl');
The rdf namespace should have a # at the end, and you should probably have one for your OWL file, too:
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl#');
But that said, there's no reason you can't try a simpler query first. Why not just run
SELECT ?s ?p ?o { ?s ?p ?o }
to be sure that you can get results, and what the data is.

Related

How to check if date in associative array and use value associated to this date With SQL Query (Mysql)

I have an associative array as follows:
$ a =
[
"2023-05-18" => 10.0
"2023-07-14" => 2.0
"2023-11-01" => 16.0
"2023-11-11" => 2.0
"2023-12-25" => 8.0
"2024-01-01" => 2.0
"2024-04-01" => 22.0
]
And in a SQL query i want to do something like:
function ($a) {
$sql = " ... some code before ...
IF (table.date IN ($a), value of date (ex 10.0), 1)
"
;
}
Not only with if with case when, or whatever the idea is to get the value in associative array according to the date (if it exist in the array);
I think the better way to do that is to concatenate the logic with your query and use a case when to handle that. something like
$s= "*\nCASE\n";
foreach ($yourArray as $dateKey => $dateValue) {
$s .= "WHEN DATE_FORMAT(table.date, '%Y-%m-%d') = '" . $dateKey . "' THEN
" . $dateValue . " \n"
;
}
$s .= "END\n";
And in you query you can directly do something like
"query do something
". $s ."
do something again "
I hope this would help
Your description of what you want is not very clear, but from the conversation and a bit of assumption I think it probably boils down to:
"list all the values from the PHP array where the date key matches at least one row from the SQL table"
If so, then here's one way you could do it:
Run a query which returns a distinct list of dates from the table where the date matches one of the keys in the array. This effectively gives you a list of dates which appear in both the array and the database.
Loop through that list to show the values matching those array keys.
Now here's some sample code. There may be a more efficient way to do it, but this is my initial thought:
$a =
[
"2023-05-18" => 10.0,
"2023-07-14" => 2.0,
"2023-11-01" => 16.0,
"2023-11-11" => 2.0,
"2023-12-25" => 8.0,
"2024-01-01" => 2.0,
"2024-04-01" => 22.0
];
$dates = array_keys($a);
$params = array_fill(0, count($dates), "?");
//sql to get all rows from database which match dates in the array
$sql = "SELECT `date` from `table` WHERE `date` IN (".implode(",", $params).")";
echo $sql; //just for debugging
//let's assume you're using PDO and have a connection object named $pdo, for the sake of argument
$stmt = $pdo->prepare($sql);
$result = $pdo->execute($dates);
$data = $result->fetchAll(PDO::FETCH_ASSOC);
//loop the returned set of matching dates
foreach ($data as $row)
{
//output values from the original array which match the dates returned from the database
echo $a[$row["date"]].PHP_EOL;
}
Related documentation:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/function.implode.php
https://www.php.net/manual/en/function.array-fill.php

PDO: fetchAll assign array variables

I have been fighting with this small line of code for about 2 hours now, researching with it and trying to figure out where I went wrong. After 9 hours of coding, I hit this little problem and now I'm in deep water. I have a 3800 line code at this point that relied on this and it's dead in the water.
The problem is that none of the final variables are coming back with any information, they're coming back entirely blank/null. When I try to assign "myname" with "$getranks['nickname']", it doesn't even do anything, even though my "print_r($getranks)" comes back with ALL of that information. I also tried fetch instead of fetchAll, but then I only get one result.
I took an old MYSQL website I made for a group on the internet which was subject to SQL Injection, so I remade it using PDO entirely. This is the problem I have.
Any help is much appreciated. I've got a headache and I'm going to go grab a late dinner while I wait for assistance. Thanks everyone.
The Code: "index.php"
$myid = $_SESSION['user'];
echo "User Session ID #" . $myid . ".<br><br>";
if(!empty($_SESSION['user'])) {
$checkrank = $db->prepare("SELECT * FROM logins WHERE id = :myid");
$checkrank->bindParam(':myid',$_SESSION['user']);
$checkrank->execute();
$getranks = $checkrank->fetchAll(PDO::FETCH_CLASS);
print_r($getranks);
$myname = $getranks['nickname'];
$mycallsign = $getranks['callsign'];
$mystatus = $getranks['status'];
$mycallnum = $getranks['callnumber'];
$myrank = $getranks['rank'];
$mynote = $getranks['note'];
$mybadge = $getranks['mybadge'];
echo "<br><br>Check rank passed, the query came back with information.<br/>";
echo "The session ID used to retrieve this information in the query was: " . $myid;
echo "<br> Your name is " . $myname . ".";
}
The Result:
User Session ID #0102.
Array ( [0] => stdClass Object ( [id] => 0102 [badge] => 201 [rank] => 6 [nickname] => Rodger Anderson [username] => MASKED [password] => MASKED [salt] => MASKED [email] => MASKED [note] => [callsign] => [profile] => http://www.MASKED.net/forums/member.php?MASKED [callnumber] => [status] => ) )
Check rank passed, the query came back with information.
The session ID used to retrieve this information in the query was: 0102
Your name is .
You are SESSION[0102]
Your name is [] and your badge number is #.
The OLD Code:
$myid = $_SESSION['user'];
echo "User Session ID #" . $myid . ".<br><br>";
if(!empty($_SESSION['user'])) {
$query = mysql_query("SELECT * FROM logins WHERE id = $myid");
$getranks = mysql_fetch_assoc($query);
$myname = $getranks['nickname'];
$mycallsign = $getranks['callsign'];
$mystatus = $getranks['status'];
$mycallnum = $getranks['callnumber'];
$myrank = $getranks['rank'];
$mynote = $getranks['note'];
$mybadge = $getranks['mybadge'];
echo "<br><br>Check rank passed, the query came back with information.<br/>";
echo "The session ID used to retrieve this information in the query was: " . $myid;
echo "<br> Your name is " . $myname . ".";
}
$getranks is an array of objects, not an associative array. Look at the results from your print_r($getranks).
You should be doing something like
$myname = $getranks[0]['nickname'];
Or use PDO::FETCH_ASSOC but even then you'll need the [0].

how can i select this item in array?

Hello i made this query for wordpress plugin
$anyOne = $wpdb->get_results("SELECT MAX(id) as idlastest FROM " . $table_name_for_select . " WHERE drJlDate='".$dkdrbooking_for_compare."'");
the value in $anyOne is
Array ( [0] => stdClass Object ( [idlastest] => 32 ) )
I need to get 32 to use it in another query, but i can't select that. How can I get idlastest from this array ?
I tried this code, but it didn't work
echo 'lastestID is : '.$myIds[0]['idlastest'];
As you want to fetch single record use get_row function instead of get_results. And if you want to get results in array instead of object you can pass argument "ARRAY_A" in function as below.
//Change in query
$anyOne = $wpdb->get_row("SELECT MAX(id) as idlastest FROM " . $table_name_for_select . " WHERE drJlDate='".$dkdrbooking_for_compare."'",ARRAY_A);
//Fetch result
echo 'lastestID is : '.$anyOne['idlastest'];
This is an object in your array, so use -> to get object value
echo 'lastestID is : '.$myIds[0]->idlastest;

PHP array output just first value

I am trying to write data from MySQL to PHP-Array (to generate a XML file with the PHP library FluidXML ). When I echo the array, I only get the first value of it, but when I echo a variable with the same data as the array I get correct output with all the information. Let me explain more exactly:
The query to get data:
$sql = sprintf("select b.nPosID, b.nAmount, b.sName, .......");
$result = mysql_query($sql);
Then I loop trough the results:
$msg = "";
$orderArticles = [];
$orderSubArticles = [];
while($data = mysql_fetch_array($result))
{
if($data['sChange'] != null) {
$msg .= ' * ' . $data['sChange'] . ' ' . number_format($data['nAmount'] * $data['nPriceChange'], 2) . "\r\n";
$orderSubArticles[] = ['SubArticle' => [
'ArticleNo' => '0',
'ArticleName' => $data['sChange'],
'Count' => $data['nAmount'],
'Price' => $data['nPriceChange']
],];
}
if ($nPosID != $data['nPosID']) {
$msg .= " \r\n" . $data['nAmount'] . ' x ' . $data['sName'] . ' ' . number_format($data['nAmount'] * $data['nPrice'], 2) . "\r\n";
$orderArticles[] = ['Article' => [
'ArticleNo' => '0',
'ArticleName' => $data['sName'],
'ArticleSize' => '0',
'Count' => $data['nAmount'],
'Price' => $data['nPrice'],
'Tax' => '10',
'SubArticleList' => [
$orderSubArticles
]],];
}
}
Let's assume, from the SQL query I get the following correct output:
Pizza
+ extra cheese
+ extra tonno
When I echo $msg variable, I get the same correct result. But when I echo the array, I only get the first value:
Pizza
+ extra cheese
To be exactly, the output which was generated with the values from the array:
<ArticleList>
<Article>
<ArticleName>Pizza</ArticleName>
<Count>1</Count>
<Price>12.9</Price>
<SubArticleList>
<SubArticle>
<ArticleName>Extra cheese</ArticleName>
<Count>1</Count>
<Price>3</Price>
</SubArticle>
</SubArticleList>
</Article>
</ArticleList>
So the second <SubArticle> is missing (extra tonno).
Without knowing how your resultset really looks like, I am doubting your assumption is correct, that a result/row in the set really contains both subarticles. That would lastly mean all results have two subarticles and that's supposingly not the case, because then it would need to return something like sChange1, sChange2 ...
Even if the results would look something like that and contain two or more sub articles, your code only assigns one of them to the subArticles-array per result.

Unable to add data to MYSQL database from JSON file using PHP

I'm new with PHP. I'v been struggling with this task for hours now. Earlier I used json_encode to get data from MYSQL to a JSON file. Now i try to revese and add the same data from JSON file to a new MYSQL database. I have a problem with converting the array to string before passing it to MYSQL database tho. The database works and I was able to add "players" there by inserting manual values instead of the $values from array. My code looks like this:
<?php
//open connection to mysql db
$con = mysqli_connect("localhost","root","","scoreboard2") or die("Error " . mysqli_error($con));
$scorefile = file_get_contents('scores.json');
$Score = json_decode($scorefile, true);
echo '<pre>' . print_r($Score, true) . '</pre>';
foreach ($Score as $field => $value) {
// Use $field and $value here
print_r($field . '=>' . $value . '<br/>', true);
//mysqli_query($con, "INSERT INTO scores (name, score, time) VALUES ($value->name, $value->score, $value->time)");
}
//mysqli_close($con);
?>
the JSON file looks like this:
[
{"id":"22",
"name":"Jack",
"score":"2142",
"time":"196:13",
"ts":"2016-02-23 15:36:23",
"date":"2016-02-23"},
{"id":"23",
"name":"Bob",
"score":"7026",
"time":"35:54",
"ts":"2016-02-23 15:40:33"}
]
etc.. and the "error" is this:
Notice: Array to string conversion in F:\XAMPP\htdocs\JSON_MySQL\decode.php on line 13
The error
Notice: Array to string conversion in
F:\XAMPP\htdocs\JSON_MySQL\decode.php on line 13
is produced by the line
print_r($field . '=>' . $value . '<br/>', true);
(which actually is the 13th line)
where you try to convert $value which is an array (your second score object) to a string in order to concatenate it with the rest of the string
note that if you replace the error-producing line by
echo '<pre>' .$field . '=>' . print_r($value, true) . '</pre>'.'<br/>';
you get the
0=>Array
(
[id] => 22
[name] => Jack
[score] => 2142
[time] => 196:13
[ts] => 2016-02-23 15:36:23
[date] => 2016-02-23
)
1=>Array
(
[id] => 23
[name] => Bob
[score] => 7026
[time] => 35:54
[ts] => 2016-02-23 15:40:33
)
that you might originally expect
Your issue is that you are converting the data in your .json file to an array by using parameter 2 of json_decode() as true.
This is converting your objects to arrays and therefore the syntax you use in this line is wrong
mysqli_query($con, "INSERT INTO scores
(name, score, time)
VALUES ($value->name, $value->score, $value->time)");
because you are using object notation.
So change this line from
$Score = json_decode($scorefile, true);
To
$Score = json_decode($scorefile);
SO
?php
$con = mysqli_connect("localhost","root","","scoreboard2") or die("Error " . mysqli_error($con));
$scorefile = file_get_contents('scores.json');
$Score = json_decode($scorefile);
foreach ($Score as $object) {
mysqli_query($con, "INSERT INTO scores
(name, score, time)
VALUES ('{$object->name}', '{$object->score}', '{$object->time}')");
}
mysqli_close($con);
?>
Also note I quoted the values with single quotes and also wrapped the object properties in {} which is required when using object or array notation inside a double quoted literal.

Categories