how can i select this item in array? - php

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;

Related

Prints only one value from the record [duplicate]

This question already has answers here:
MySQLi query returns only one row
(3 answers)
Closed 6 years ago.
Here, I want to print those value which are in table.
So, my query is like this:
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
$roleres = mysqli_query($conn,$get_role_query);
$r_id = mysqli_fetch_assoc($roleres);
Here, 333 is not in table but 1 and 2 are in table.
When I am printing this like,
print_r($r_id);
It only gives me 1 but not getting 2 which is also in table. I don't want 333 that is fine. But I am getting only 1, not getting 2.
UPDATED BELOW:
As you all suggest to use while loop, I did like this:
$r_role = mysqli_num_rows($roleres);
for($i=0;$i<=$r_role;$i++)
{
print_r($r_id);
}
But I am getting output like this:
Array
(
[id] => 1
)
Array
(
[id] => 1
)
Array
(
[id] => 1
)
From above query, I just want output like,
Array
(
[0] => 1
[1] => 2
)
Any suggestion would be appreciated.
Thanks.
Use while in order to fetch multiple values from the table:
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
$roleres = mysqli_query($conn,$get_role_query);
while($r_id = mysqli_fetch_assoc($roleres))
{
echo $r_id['id'];
}
You can also use an object method instead array method.
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
if ($result = $mysqli->query($get_role_query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
echo $obj->id;
}
}
/* free result set */
$result->close();
You are not using mysqli_fetch_assoc() correctly. It fetches one record at a time. Use it as follows:
while($r_id = mysqli_fetch_assoc($roleres))
{
print_r($r_id);
}

How to fetch SPARQL query result using EasyRdf

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.

why i have NULL when saving data in database

I'm trying to save with foreach
here is what i get from my form
Array
(
[mulai] => 2016-08-28
[akhir] => 2016-08-31
[keterangan] => remarks
[nip] => Array
(
[0] => 1004384
[1] => 1602744
[2] => 1501039
)
)
and then here is my saving query.
$jumlahrange = $this->db->query("SELECT DATEDIFF(day,'".$mulai."','".$akhir."') AS diff")->row();
$totaldata = count($nip);
$skrg = $this->db->query("SELECT GETDATE() tgl")->row();
for($x = 0;$x<=$totaldata;$x++)
{
for($y=0;$y<$jumlahrange->diff;$y++){
$this->db->query("INSERT INTO attendance
(Nip,AttendanceDate,InTime,OutTime,AttendanceCode,RosterCode,LocationCode,Remarks,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy)
values(
'".$nip[$x]."',DATEADD(DAY,".$y.",'".$mulai."'),'','','P3','','','".$keterangan."','".$skrg->tgl."','$niplogin','','')
");
}
}
i have no problem with my save but i have empty field like this in my table. In row 10,11,12 . That row should not exist right?.
I using SqlServer 2008 and Codeigniter . I know i can use insert_batch, but i want use this way.
in your line for($x = 0;$x<=$totaldata;$x++) i'm pretty sure you wanted to write < instead of <=
To overcome these kind of issues you can use foreach loop instead
foreach($resourcedata as $value){
//your code goes here and you will get all array elements sequentially in **$value** variable
}
This one is right at your fingertips. $nip[$x] is null. Error log or dump and die on the first loop $nip[$x] and see what it returns. If it is in fact not null, then it might be a data type problem (string vs int).

MySQL/PHP/Wordpress - php result object contains members with function names - how to dereference?

in a normal SQL table i have a date field called date1. I have a query that asks for the date1 field and for the monthname and weekday of that field and outputs the raw data on a web page...
$result = $wpdb->get_results("SELECT date1, MONTHNAME(date1), WEEKDAY(date1) FROM my_table");
echo "<pre>";
print_r($result);
echo "</pre>";
with the following result:
Array
(
[0] => stdClass Object
(
[date1] => 2013-08-26
[MONTHNAME(date1)] => August
[WEEKDAY(date1)] => 0
)
)
But how do I get about dereferencing the monthname (or weekday) part of the result?
foreach($result as $i => $entry) {
$date = $entry->date1; // works as expected
$m = $entry->MONTHNAME(date1); // does not work - also as expected...
}
The result is a Fatal error: Call to undefined method stdClass::MONTHNAME().
I could use the wordpress option to obtain the query result as an array of arrays (and keep track of what index would correspond what part of the result) but is there any way to quote the variable name that happens to have the form of a method call and make it behave as an ordinary object variable?
SELECT date1, MONTHNAME(date1) AS `month`, WEEKDAY(date1) AS `week` FROM my_table
now you can use $entry->month and $entry->week

To understand an array in PHP when given the other variable in the array

Please, see Cha's answer where we are pretty close the final solution. We are debugging the code with these data
database in PostgreSQL
test sql-queries
--
Problem related to the Unsolved problem in the code
How can you refer to the php -element in the following array?
I have the following data
Array
(
[1] => Array
(
[tag] => Array
(
[0] => php
[1] => scripts
)
)
[2] => Array
(
[tag] => Array
(
[0] => ssh
[1] => network
)
)
)
where the arrays stand for tags_and_id, question_id and tag respectively.
In other words, the variable $tags_and_id has the column question_id and that still has a subcolumn tag and that still each single tag.
I would like know how you can refer to the tag php.
I run unsuccessfully getting nothing as an output
echo $tags_and_id[1]['tag'][0];
If you want to add more information about each question, you can simply add to $end_array[1].
This is the array my first foreach statement creates:
// The end result turns out to be something like this:
array(
1 => array(
'tags' => array(
0 => "php",
1 => "sql"),
)
);
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=noa user=noa password=123");
if( empty($_GET) ) {
// to get titles and question_ids
$result_titles_tags = pg_prepare( $dbconn, "query777",
"SELECT question_id, title
FROM questions
WHERE question_id IN
(
SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
)
ORDER BY was_sent_at_time
DESC LIMIT 50;"
);
$result_titles = pg_execute( $dbconn, "query777", array());
// TAGS
$result_tags = pg_prepare( $dbconn, "query9",
"SELECT question_id, tag
FROM tags
WHERE question_id IN
( SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
);"
);
$result_tags = pg_execute( $dbconn, "query9", array());
and the code in the question initially
// Go through each Tag
while( $tags_and_Qid = pg_fetch_array( $result_tags )) {
// Add the Tag to an array of tags for that question
$end_array [ $tags_and_Qid['question_id'] ] ['tag'] [] = $tags_and_Qid['tag'];
}
// First compile the Data
// Go through each question
while( $titles_and_Qid = pg_fetch_array( $result_titles ) ) {
echo ("<div class='question_summary'>"
. $titles_and_Qid['title']
// Problem here!
// How can you print the titles such that
// they are assigned to each tag -set?
);
$i = 0;
// Then Loop Through each question
foreach( $end_array as $tags_and_Qid['question_id'] => $tags_and_Qid['tag'] )
{
echo ("\n\nITERATION NUMBER IS " . $i); // The code is buggy here
// For instance, we get 9 iterations for 3 questions
// Create the starting HTML
echo ("<div class='tags'>");
// Go through each tag
// not sure about this
foreach( $end_array[$tags_and_Qid['question_id']] ['tag'] as $tag )
{
echo ( "<a class='post_tag' href='?tag="
. $tag
. "'>"
. $tag
. "</a>"
);
}
// end the html
echo '</div>';
$i++;
}
echo ("</div>");
}
// to end the list of questions
echo ("</div>"
);
}
?>
If print_r is failing, then something is wrong before that. Your data is probably not being structured in the way you think it is being structured.
And can I just recommend that if you only have the tag and the question name, you just store as a single level array that looks like the following:
array(
'php' => '7',
'sql' => '7',
'python' => '3'
)
If you have other things you're going to store then yeah, you'll have to do what you're doing. In that case, if you can't access the array with the keys in brackets, then your keys are probably not what you think they are, or there is something wrong with your code somewhere.
I looked at your code, and why are you accessing query results like $row[0], instead of $row['question_id'] ?
Also, you can't print_r($result_tags) , because data from a query is not actually stored by PHP, it is only referenced. therefore you have to use a while loop to go through it, as the script will call one row of results at a time.
You say: foreach( $result_tags as $question_id => $data ) This doesn't make sense, because there is no value for $result_tags except for a reference to the query that can be used to call one row of results at a time. Instead you want to do:
while( $row2 = pg_fetch_array( $result_tags )) {
$question_id = $row2['questions_question_id'];
$data = $row2['data'];
$end_array[$question_id]['tags'][] = $data;
// you can't have your $data['tag'] as that refers to the
// value of an array that doesn't exist
}

Categories