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.
Related
I need to add a UNIQUE ID and a string that is with that ID , into an array. This array needs to be updated too. Example:
ID NAME[(3,Flor)(5,Dries)] Then I need to have a check when I want to insert a new value in this array if the ID already is in the array or not. I currently have this:
$werknemers= [];
while($werknemer= $werknemersql->fetch_assoc()){
$werknemerid = $werknemer['userid'];
$naam = $werknemer['name'] ." " . $werknemer['familyname'];
array_push($werknemers, array("id" => $werknemerid, "naam" => $naam ));
}
echo $werknemers[1][1];
A simple technique to achieve that is to always update the array, with a consistent index:
$werknemers = [];
while($werknemer = $werknemersql->fetch_assoc()){
$werknemerid = $werknemer['userid'];
$naam = $werknemer['name'] . " " . $werknemer['familyname'];
$index = $werknemerid . '.' . $naam;
$werknemers[$index] = ["id" => $werknemerid, "naam" => $naam];
}
And then, if necessary, get rid of the indexes:
$werknemers = array_values($werknemers);
$werknemers= [];
while($werknemer= $werknemersql->fetch_assoc()){
$werknemers[$werknemer['userid']] = $werknemer['name'] . " " . $werknemer['familyname'];
}
Use id as index and it's solved :)
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.
I am using Pear PHP and HTML quickforms to create a dropdown, concatenate results and maintain them in a drop down.
Code that fetches the data and concatenates:
DO_Common::DebugLevel(1);
$stDO = DO_Common::factory('SoftwareTypes');
$lmDO = DO_Common::factory('LicenseMethods');
$tDO = DO_Common::factory('sldSoftwareType');
$stDO->selectAdd();
$stDO->selectAdd('Title, Method, sldSoftwareType.Type, SoftwareTypes.ID');
$stDO->joinAdd($lmDO);
$stDO->joinAdd($tDO);
$stDO->whereAdd("SoftwareTypes.Flag <> 1");
$stDO->find();
$lmst = array();
while ($stDO->fetch())
{
$lmst[] =$stDO->ID . "| " . $stDO->Title . " | " . $stDO->Method . " | " .$stDO->Type ;
// $text = array_column($lmst[], $stDO->ID);
}
Dropdown creation code:
$ddlSoftwareType = $form->addElement('select', 'ddlSoftwareType', 'Software Type', $lmst, array('id' => "SoftwareTypeList", 'orderBy' => "Type", "OnChange" => "GetDetails();"));
Although this works perfectly I want to be able to add the ID of the original table as the value of the dropdown.
Is this possible?
I'm trying to convert an array (key/value) to be an SQL statement.
I'm using MYSQLi like such:
if(!$result = $mysqli->query($sql)){throw new Exception("SQL Failed ".__file__." on line ".__line__.":\n".$sql);}
I have an array like such:
Array
(
[database] => Array
(
[cms_network] => Array
(
[network_id] => 61
[network_name] =>
[network_server_mac_address] => 00:1b:eb:21:38:f4
[network_description] => network
[network_thermostat_reporting_rate] => 5
[network_server_reporting_rate] => 5
[network_data_poll_rate] => 5
[network_created_by] => 38
[network_modified_by] => 1
[network_network_id] => 8012
[network_language] => en
[network_hotel_id] => 68
[network_channel] => 0
[network_deleted] => 0
[network_reported_network_id] => 8012
[network_rooms] => 4
)
)
)
How can I convert [cms_network] to look like this:
$sql = "UPDATE cms_network set network_id='61', network_name='',
network_server_mac_address = '00:1b:eb:21:38:f4', .... WHERE network_id='61'"
I'm more interested in knowing how to concatenate the key=>value pair of the array to be key='value' in my select statement.
Thanks for the help!
If you use the VALUES syntax, you could do it in one fell swoop.
mysql_query("
UPDATE MyTable
( . implode(',', array_keys($array['database']['cms_network'])) . ")
VALUES ('" . implode("','", $array['database']['cms_network']) . "')
");
This, of course, assumes that the data is already escaped.
EDIT: Tidier version that's easier to read and maintain:
$fields = implode(',', array_keys($array['database']['cms_network']));
$values = implode("','", $array['database']['cms_network']);
mysql_query("UPDATE MyTable ($fields) VALUES ('$values')");
I suggest you populate an array with formatted key/value pairs, then implode them at the end. This is an easy way to add the required , between each key/value:
$fields = array();
foreach($array['database']['cms_network'] as $key => $value) {
// add formatted key/value pair to fields array
// e.g. format: network_id = '26'
$fields[] = $key . " = '" . $value . "'";
}
$fields = implode(', ', $fields);
// build your query
$query = "UPDATE cms_network SET " . $fields . " WHERE network_id = " . $array['database']['cms_network']['network_id'] . " LIMIT 1";
// process it...
This will (SQL wise) be inserting every value as a string, which is obviously incorrect with integer columns etc. It should still work anyway, but if not you'll need to put in a conditional statement for whether to wrap the value in quotes or not, like this:
foreach(...) {
if(is_numeric($value))
$fields[] = $key . ' = ' . $value;
else
$fields[] = $key . " = '$value'";
}
Although this should probably relate to your database column type rather than the PHP variable type. Up to you, they should work fine with quotes around integers.
This should work.
$update_query = "UPDATE `cms_network` SET ";
$count = 0;
foreach($array['database']['cms_network'] as $key => $value) {
if ($count != 0) {
$update_query = $update_query.",".$key."=".$value;
} else {
$update_query = $update_query.$key."=".$value;
}
$count++;
}
$update_query = $update_query." WHERE ".cms_network."=".$array['database']['cms_network'];
mysql_query($update_query);
Very basic question.. but I'm missing the point.. I have this data on my table:
ID SITEID SECTION
1 1 posts
2 2 posts
3 1 aboutme
4 1 contact
5 2 questions
The output is an array. I can't change it.
I want to make this output on php with a single for loop with that array:
<h1> sections for site 1 </h1>
posts
aboutme
contact
<h1>sections for site 2 </h1>
posts
questions
I'm trying to do something like this, where $sectionsArray is my output. And I want to check if siteid is the same, then make a loop..
for ($j = 0; $j < sizeof($sectionsArray); $j++) {
while (siteid == 1) {
echo '<h1>' . $sectionsArray['siteid'] . '</h1>';
}
echo "' . $sectionsArray['section'] . ';
}
But I don't get the logic of "grouping" the results with a while.. INSIDE a loop. Any light will be welcome.
Thanks
You can't really do this with just 1 loop, assuming you can't change the query. As you for loop through $sectionsArray, you have to deal with each row as you encounter it. It doesn't matter if you only want sections for site 1, you'll still encounter sections for site 2, 3, etc & either ignore them or deal with them.
If you can change your query, have it order by SITEID, then ID. That'll group all sections by site (note: this is not the same as using the SQL GROUP BY statement).
If you can't change your query, use your for loop to iterate through $sectionsArray once. In that loop, build a second array with the different sections ordered by site id. Iterate through that second array to output all the sections which are now in site id order.
Quick and dirty ;)
<?php
$arr = array(
array('id' => 1, 'site_id' => '1', 'section' => 'posts'),
array('id' => 2, 'site_id' => '2', 'section' => 'posts'),
array('id' => 3, 'site_id' => '1', 'section' => 'aboutme'),
array('id' => 4, 'site_id' => '1', 'section' => 'contact'),
array('id' => 5, 'site_id' => '2', 'section' => 'questions')
);
$htmlStrings = array();
$curr_site_id = '0';
foreach($arr as $item)
{
if ( $item['site_id'] != $curr_site_id )
{
$curr_site_id = $item['site_id'];
if ( !isset($htmlStrings[$curr_site_id]) ) $htmlStrings[$curr_site_id]['header'] = '<h' . $curr_site_id . '>Sections for site ' . $curr_site_id . '</h' . $curr_site_id . '>';
$htmlStrings[$curr_site_id]['content'] .= '<br />' . $item['section'];
}
else
{
$htmlStrings[$curr_site_id]['content'] .= '<br />' . $item['section'];
}
}
foreach($htmlStrings as $section)
{
echo $section['header'];
echo $section['content'];
}
If you want to do one pass on the array, first sort (technically, that's also a pass!) and then check for a change in siteid as you loop through it. Here's how you can sort the array by siteid before looping through it:
$sections = array(
array('id'=>1, 'siteid'=>1, 'section'=>'posts'),
array('id'=>2, 'siteid'=>2, 'section'=>'posts'),
array('id'=>3, 'siteid'=>1, 'section'=>'aboutme'),
array('id'=>4, 'siteid'=>1, 'section'=>'contact'),
array('id'=>5, 'siteid'=>2, 'section'=>'questions'),
);
usort($sections, 'sortBySiteId');
function sortBySiteId($a, $b)
{
if ($a['siteid'] == $b['siteid']) {
return 0;
}
return ($a['siteid'] < $b['siteid']) ? -1 : 1;
}
thanks.. but I ended up doing this:
for ($j=0;$j<sizeof($sectionArray);$j++) {
$section_id = $sectionArray[$j]['id'];
$section_name = $sectionArray[$j]['secao'];
echo '<div id="menu">';
echo '<div class="section">'.$section_name.'</div>';
$categoryArray = $objectCategory->listCategory($section_id); // return my array from db
for ($ii=0;$ii<sizeof($categoryArray);$ii++) {
$categoryId = $categoryArray[$ii]['id'];
$categoryName = $categoryArray[$ii]['category'];
echo "<div class=\"item\">";
echo "$categoryName";
echo "</div>";
}
echo '</div>';
}
Is that ok? I mean, I have some problems with arrays... :(
But thanks anyway