SQL Results as PHP Array - php

I am trying to solve this. Maybe this is absolutly incorrect, I need some help.
I have a table like this:
INSERT INTO `municipios` (`id`, `provincia`, `municipio`) VALUES (1, 1, 'Alegría-Dulantzi'), (2, 1, 'Amurrio'), (3, 1, 'Añana'), (4, 1, 'Aramaio'), (5, 1, 'Armiñón'),
And this is my handler:
$query = "SELECT * FROM municipios WHERE provincia='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$groups = array(
$row{'id'} => array(
'name' => $row{'municipio'},
'description' => 'Agrupación electoral de ' . $row{'municipio'},
'status' => 'public',
'enable_forum' => 1,
),
);
}
With this I got just the last result. I have tried another options, but doesn´t work.

Something like this should solve your issue:
$groups[] = array(
$row['id'] => array(
'name' => $row['municipio'],
'description' => 'Agrupación electoral de ' . $row['municipio'],
'status' => 'public',
'enable_forum' => 1,
),
);
However, may i suggest your use PDO. There is a pretty good article http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ that should get you going in the right direction.

Is this an issue with the way you're appending the groups array? I think your overwriting the array every time u set a value. Try using array_push() to append to groups.
Let us know of that helps!
array_push()
http://php.net/manual/en/function.array-push.php

Related

make multilevel array from mysql php

i have this array in an example, how can i get the same result from query from database?, i need to replace the values which the values of the database.
$data = array(
array(
'qty' => 1,
'Price' => 1.00,
'total' => 1.00
),
array(
'qty' => 2,
'Price' => 1.00,
'total' => 2.00
),
array(
'qty' => 3,
'Price' => 1.00,
'total' => 3.00
)
);
then in the example use the nusoap lib
foreach($data as $concept) {
$par['Concepts'][] = new soapval('Concept', 'Concept', $concept);
}
so i need to call the query:
$query_data_cot = mysql_query("SELECT * FROM data WHERE id='1'");
while($data_quote=mysql_fetch_array($query_data_cot)){
$conceptosDatos[]["qty"]=$data_quote['qty'];
$conceptosDatos[]["Price"]=$data_quote['price'];
$conceptosDatos[]["total"]=$data_quote['total'];
}
but when i do these i got an error
Error: Array ( [faultcode] => soap:Server [faultstring] => Server was unable to process request. --->
thank you
Everytime you use $conceptosDatos[]... the [] will create a new subarray. So your result will be something like this
array(
array('qty' => ..),
array('Price' => ..),
array('total' => ...),
array('qty' => ..),
array('Price' => ..),
array('total' => ...),
...
)
Instead you need to create a new subarray only for a whole set, so use something like this
$query_data_cot = mysql_query("SELECT qty, price, total FROM data WHERE id='1'");
while($data_quote=mysql_fetch_assoc($query_data_cot)){
$conceptosDatos[] = $data_quote;
}
Of course you could also do it like this
$query_data_cot = mysql_query("SELECT qty, price, total FROM data WHERE id='1'");
while($data_quote=mysql_fetch_assoc($query_data_cot)){
$conceptosDatos[] = array(
'qty' => $data_quote['qty'],
'Price' => $data_quote['price'],
'total' => $data_quote['total'],
);
}
But why write every field if you're going to copy the whole array anyway?
If you need to use different names (as in your example price and Price), you can either change your db schema or use aliases in your query, giving you this code:
$query_data_cot = mysql_query("SELECT qty, price AS Price, total FROM data WHERE id='1'");
while($data_quote=mysql_fetch_assoc($query_data_cot)){
$conceptosDatos[] = $data_quote;
}
This has the advantage that if you wish to modify your code in the future, you'd only need to modify the query (and could probably encapsulate this logic inside a function) - so less work for future you.
By the way, did you see the big red box in the manual on all mysql_* methods's sites? It's deprecated and PDO as well as MySQLi are way better alternatives. This helps decide what to use.
Try this , while($data_quote=mysql_fetch_array($query_data_cot , MYSQL_ASSOC )) , as you are retrieving the $data as an associative array .
Each assignment line in your loop is creating a new element of the $conceptDatos array, not filling in a different element of the same element. So your array looks like:
array(
array('qty' => 1),
array('Price' => 1.0),
array('total' => 1.0),
array('qty' => 2),
array('Price' => 1.0),
array('total' => 1.0),
...
)
Your loop shoud be:
while($data_quote=mysql_fetch_array($query_data_cot)){
$conceptDatos[] = array(
'qty' => $data_quote['qty'],
'Price' => $data_quote['price'],
'total' => $data_quote['total']
);
}

How to turn sql result to multi-dimensional array dynamically?

Here is the query string.
$query = "SELECT t.id, t.assignee, t.owner,
d.code, d.status, d.target_completion_date,
d.target_extension_date, d.submission_date, d.approval_date,
d.revision_start_date, d.revision_completion_date, d.message,
ty.name, f.orig_name, f.new_name,
b.payment_date, b.discount, b.total_cost, b.amount_payed, b.edit_level,
b.billing_type, b.pages, b.words
FROM tasks t
INNER JOIN details d ON t.detail_id = d.id
INNER JOIN billing b ON t.billing_id = b.id
INNER JOIN TYPE ty ON d.document_type_id = ty.id
INNER JOIN files f ON t.file_id = f.id
WHERE t.assignee = 'argie1234'";
And this is the array i would like the query result to turn into.
$user = array('allTask'=>array(array('taskid' => 1,
'assignee'=>'argie1234',
'owner'=>'austral1000',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' =>'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
array('taskid' => 12,
'assignee'=>'argie1234',
'owner'=>'usaroberto',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' => 'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
'account' => array( 'username' => 'marooon55',
'emailadd' => 'marooon#yahoo.com',
'firstname' => 'Maroon',
'initial' => 'E',
'lastname' => 'Young',
'country' => 'Australia',
'gender' => 'M',
'password' =>'360e2801190744a2af74ef6cbfdb963078b59709',
'activationDate' => '2013-09-13 14:30:34') );
How can i create the above array? I sure know how to define multi dimensional array, regretfully though i am having difficulty creating this complex array dynamically. As a beginner i don't even know where to begin.
Here is an example that might help you out. Try starting with simple multi dimensional arrays, once you get a hold of it, you can move onto building complex ones. You will then find that the array you want to build is not really difficult than you initially thought it to be.
$mycomplexarray = array('key1' => array('val1', 'val2'),
'key2' => array('val3', 'val4' => array('val5', 'val6')
)
);
You could create the array just as you have here. I'm not gonna write the whole thing out, but something like this...
$result = $mysqli->query($query); // however you query the db is up to you.
$row = $result->fetch_assoc(); //same as query use your prefered method to fetch
$user = array('allTask'=>array(array('taskid' => $row['id'],
'assignee'=>$row['assignee'],
'owner'=>$row['owner'],
'details' => array( 'code' => $row['code'],
'status'=>$row['status'],
...etc, Hope this makes sense for you.
Set up a structure array first that defines which columns will be stored in a sub array like
$struc=array('Id'->0, 'assignee'->0, 'owner'->0,
'code'->'detail', 'status'->'detail', 'target_completion_date'->'detail',
'target_extension_date'->'detail', 'submission_date'->'detail', 'approval_date'->'detail',
'revision_start_date'->'detail', 'revision_completion_date'->'detail', 'message'->'detail',
'name'->'file', 'orig_name'->'file', 'new_name'->'file',
'payment_date'->'billing', 'discount'->'billing', 'total_cost'->'billing', 'amount_payed'->'billing', 'edit_level'->'billing', 'billing_type'->'billing', 'words');
In your while ($a=mysqli_fetch_assoc($res)) loop you can now use this structure to decide whether you want to store an element directly in your target array or whether you want to place it in the subarray named in this structure array. Like
$res=mysqli_query($con,$sql);
$arr=array();
while($a=mysqli_fetch_assoc($res)) {
// within result loop: $a is result from mysqli_fetch_assoc()
$ta=array(); // temp array ...
foreach ($a as $k => $v){
if ($struc[$k]) $ta[struc[$k]][$k]=$v;
else $ta[$k]=$v;
}
$arr[]=$ta; // add to target array
}
This is the complete code, no more is needed. It was typed up on my iPod, so it is NOT tested yet.
The generated array should be equivalent to your $user['allTask'] array.

Recursively merge two arrays, or replace with latter based on a key

This should be a really easy answer and I'm probably just being thick, but I have two arrays in PHP:
$data1 = array(
array(
'qid' => 'q-prof-1-1',
'value' => 10,
),
array(
'qid' => 'q-prof-2-1',
'value' => 3,
),
);
$data2 = array(
array(
'qid' => 'q-prof-2-1',
'value' => 5,
),
array(
'qid' => 'q-prof-3-2',
'value' => 1,
),
);
And I want to result in:
$result = array(
array(
'qid' => 'q-prof-1-1',
'value' => 10,
),
array(
'qid' => 'q-prof-2-1',
'value' => 5,
),
array(
'qid' => 'q-prof-3-2',
'value' => 1,
),
);
... so that the two will be merged- but, if it finds a qid that matches another, will replace it with the latter.
I've tried a mixture of array_merge(), array_merge_recursive(), $data1 + $data2, $data2 + $data1, array_replace(), array_replace_recursive(), array_diff() etc, etc, but every options seems to return either two or four values rather than the three. And of course I've done my fair share of S.O hunting.
Any ideas? Would prefer something short and sweet to a massive iterating function of any sort!
Thanks in advance :)
Matt
Edit:
I've just realised that if I turn the arrays inside $data1 & $data2 into key-value pairs most of those merge and replace functions work, eg:
$data1 = array(
'q-prof-1-1' => array(
'qid' => 'q-prof-1-1',
'value' => 10,
) // ... etc etc
);
... but I'd still rather not have to change the original data
Is there a reason you can't use an associative array? That way you can just have
$array = array('q-prof-1-1' => 10, 'q-prof-2-1' => 3);
$array2 = array('q-prof-2-1' => 5, 'q-prof-3-2' => 1);
Then just loop through $array2, push the value on if $array doesn't have a key (key_exists() if i remember right) or if it does have a key merge them how you want?
Also, but not sure, using an associative array would probably make array_merge work correctly (possibly).

Codeigniter how to not select duplicated id's

I've got a database and the fetched array looks something like this (if i was creating the arrays my self)
<?php
$array[] = array('id' => 1, 'message' => 'test');
$array[] = array('id' => 1, 'message' => 'test');
$array[] = array('id' => 2, 'message' => 'test');
$array[] = array('id' => 5, 'message' => 'test');
$array[] = array('id' => 1, 'message' => 'test');
$array[] = array('id' => 8, 'message' => 'test');
$array[] = array('id' => 5, 'message' => 'test');
$array[] = array('id' => 1, 'message' => 'test');
?>
As you can see, there is a few arrays with the ID 1, and i wanna select the last 5 items but if there is a duplicate, i wanna skip it, and move on. Is there any easy solution for this?
Are you using the Active Record Class?
If so add this line to your query, before your get your results:
$this->db->distinct();
For current and future reference CI has and is praised for it's brilliant Documentation!
It is always worth taking a look there too:
http://codeigniter.com/user_guide/database/active_record.html
If you don't use the Active Record Class, do as suggested above :).
you should use a query like this:
"SELECT DISTINCT id,message FROM your_table LIMIT 0,5"
MySQL Method:
Reference this article # w3schools: http://www.w3schools.com/sql/sql_distinct.asp
SELECT
DISTINCT(table.id),
table.message
FROM
db.messages
If you are adamant on doing this outside of the prefferred method of using MySQL you can use PHPS array_unique() function..
http://php.net/manual/en/function.array-unique.php
<?php
$result = array_unique($array);
print_r($result);

how to show data from 3 combinational table using codeIgniter

I have three database tables, question_set, question and answer.
question_set contains set_name and set_id
question contains question and also question_set_id
answer contains answer , question_id
I can not work out a way to show all the data in one view file,
I tried joins but then question data is repeating with it prints because every question has three or four answer.
Just thought I would point out.
Your database design is horrible.
It will not scale well, and infact I do not think it would actually. work.
The way I would do it is
Three tables
sets => id, name
questions => id, set_id, question
answers => id, set_id, question_id, answer, points
Note that in my above example I am taking it one step further, rather than each answer being true or false, it can have an assigned point value.
hence, an answer that you deemed half correct could be given 5 points, where as a correct answer could be given 10 points, it also works as a boolean true, just have a correct answer as 1 point, and an incorrect answer as 0 points
Anyway.
With the above table design in mind.
You could do
$this->db->select('s.id as set, s.name as name, q.id as qid, q.question as qu, a.id as aid, a.answer as an, a.points as p')
->from('sets s')
->join('questions q', 'q.set_id = s.id')
->join('answers a', 's.set_id = s.id')
->where('s.id', 'SET ID');
$questions = $this->db->get();
$set = array('questions' => array());
foreach($questions as $s){
$set['id'] = $s->set;
$set['name'] = $s->name;
$set['questions'][$s->qid]['id'] = $q->qid;
$set['questions'][$s->qid]['question'] = $q->qu;
if(!isset($set['questions'][$s->qid]['answers']))
$set['questions'][$s->qid]['answers'] = array();
$set['questions'][$s->qid]['answers'][] = array(
'id' => $q->aid,
'answer' => $q->an',
'points' => $q->p
);
}
So then you end up with an array that looks something like
array(
'id' => 1,
'name' => 'My first quiz',
'questions' = array(
array(
'id' => 1,
'question' => 'What is 1+1+1?',
'answers' => array(
array(
'id' => 1,
'answer' => 1,
'points' => 0
),
array(
'id' => 2,
'answer' => 2,
'points' => 0
),
array(
'id' => 3,
'answer' => 3,
'points' => 1
)
)
),
array(
'id' => 2,
'question' => 'What is 2+2+2?',
'answers' => array(
array(
'id' => 4,
'answer' => 6,
'points' => 1
),
array(
'id' => 5,
'answer' => 2,
'points' => 0
),
array(
'id' => 6,
'answer' => 3,
'points' => 0
)
)
)
)
);
Then you can do.
echo '<h2>'.$set['name'].'</h2>';
foreach($set['questions'] as $q){
echo '<div class="question">';
echo '<h3>'.$q['question'].'</h3>';
echo '<div class="answers">';
foreach($q['answers'] as $a){
echo '<label for="a'.$a['id'].'">'.$a['answer'].'<input type="checkbox value="'.$a['id'].'" name="q'.$q['id'].'" /></label><br />';
}
echo '</div>';
echo '</div>';
}
The easiest way, but which of course requires more SQL calls, is to use nested loops for this.
1) Join the question set and question tables
2) For each entry in the result set, retrieve the answers for that entry and put it in a separate array, nested in a bigger array where the key is the id of the question.
Your view would then look something like this:
foreach($questions as $question)
{
//Print question information
$answers = $answers_array[$question['id']];
foreach($answers as $answer)
{
//Print answers information
}
}
Might not be best practice but it will do the trick.

Categories