building a multi dimentional array from mysqli database query using php - php

I am trying to build a multi dimentional array of students and their data from my database table using mysqli and php.
I want my array to look something like this
Array #$adult array
(
[626] => Array #student no 626 data
(
[name] => emily,
[age] => 43,
[height] => 156,
)
[627] => #student no 627 data
(
[name] => luke,
[age] => 31,
[height] => 176,
)
)
the number being the members id followed by their data.
So i have tried the following
$sql = "SELECT * FROM pzgym_waitinglist WHERE seen = 0 GROUP BY gym_discipline, school_yr, id";
$result = $db->query($sql);
if ($result->num_rows > 0)
{
#set up array
$adult = array();
while($row = $result->fetch_array())
{
$id = $row["id"];
$name = $row["name"];
$age= $row["age"];
$height = $row['height'];
if($row['gym_discipline'] == "Adult Gymnastics")
{
$adult[$id] = "['name'] => $name, ['age'] => $age, ['height'] => $height";
}
}
}
but this isnt producing the correct results, so im guessing my array building sucks :( here is what i am getting.
Array
(
[626] => ['name'] => Emily, ['age'] => 43, ['height'] => 156
[627] => ['name'] => Luke, ['age'] => 31, ['height'] => 176
)
Could someone help me please to build a successful multi dimentional array from the data im my database
Many Thanks

You need a second level when you create the array, instead of just simply adding keys and data to the array.
So, first create an index (key) with the student ID, then the value of that new index will be a sub-array with all the data for that student.
Then next loop it will do the same for the next student.
Something like:
while($row = $result->fetch_array())
{
$id = $row["id"];
$name = $row["name"];
$age= $row["age"];
$height = $row['height'];
if($row['gym_discipline'] == "Adult Gymnastics")
{
$adult[$id] = array(
"name" => $name,
"age" => $age,
"height" => $height,
);
}
}

Use the array construct:
$adult[$id] = array('name' => $name, 'age' => $age, 'height' => $height);

You need to do in following manner--
$adult[$id]['name'] = $name;
$adult[$id]['age'] = $age;
$adult[$id]['name'] = $height;
Note:- if condition is not required because your array is created through id.

Related

How to insert an array of data into the database using PHP?

I am getting the array value like below
Array
(
[0] => Array
(
[upload_label] => label 1
[upload_name] => 100-best_1940225136.png
[society_id] => 57
)
[1] => Array
(
[upload_label] => label 2
[upload_name] => 150x150_2147441709.png
[s_id] => 57
)
)
Now I have to insert the data into the database. So I used below inert code
$sqlUpload="INSERT INTO `tbl_uploadAll`(upload_label,upload_name,s_id) VALUES (:upload_label,:upload_name,:s_id)";
$stmt= $pdo->prepare($sqlUpload);
$stmt->execute($dataupload);
when I hit the button then am getting 500 error in the network tab
My full code here
if (isset($_POST['send'])) {
$total = count($_FILES['docUpload']['name']);
$dataupload=array();
for($i=0; $i < $total; $i++) {
if(isset($_FILES['docUpload']['name'][$i]) && $_FILES['docUpload']['name'][$i] != "")
{
$foldername="profile";
$uploadLabel=$_POST['docUploadLabel'][$i];
$image1 = $_FILES['docUpload']['name'][$i];
$filename = basename($image1);
$onlyfile = pathinfo($filename, PATHINFO_FILENAME);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$file = mt_rand();// random number
$newname = $onlyfile.'_'.$file.'.'.$extension;
//$location='images/'.$foldername.'/'.$newname;
$location='../assets/images/uploads/'.$foldername.'/'.$newname;
if($extension=='png' || $extension=='jpg' || $extension=='jpeg') {
compressImage($_FILES['docUpload']['tmp_name'][$i],$location,60);
}
else{
move_uploaded_file($_FILES['docUpload']['tmp_name'][$i], $location);
}
$uploadDoc=$newname;
$dataupload[]=array(
'upload_label'=>$uploadLabel,
'upload_name'=>$uploadDoc,
's_id'=>$last_id,
);
}
}
echo"<pre>";
print_r($dataupload);
$sqlUpload="INSERT INTO `tbl_uploadAll`(upload_label,upload_name,s_id) VALUES (:upload_label,:upload_name,:s_id)";
$stmt= $pdo->prepare($sqlUpload);
$stmt->execute($dataupload);
}
You are passing array of array
$stmt->execute($dataupload);
execute expects an array of key => value where key should be named placeholders. Like
$data = [
'name' => $name,
'surname' => $surname,
'sex' => $sex,
];
So for your case, you should execute inside a foreach
foreach ($dataupload as $row)
{
$stmt->execute($row);
}

Php array and json

help me to convert the following array in to json.
I tried to convert the array.
Array
(
[0] => Array
(
[c_code] => 200001
[itemname] => 303 10CAP
[c_pack_code] => PK0075
[c_web_img_link] =>
)
[1] => Array
(
[c_code] => 200005
[itemname] => 3P 4TAB
[c_pack_code] =>
[c_web_img_link] =>
)
)
current result for the following code is
public function searchOrder($idx, $data) {
if (!empty($data)) {
$result = OrderbukModel::func_get_searchlist($idx,$data);
if (!empty($result)) {
$resultArray[] = $result;
print_r(json_encode($result));
} else {
$resultArray[$idx] = ["Mysql returns empty result !"];
print_r(json_encode($resultArray));
exit;
}
}
}
now i got the result is like
[{"c_code":"200001","itemname":"303 10CAP","c_pack_code":"PK0075","c_web_img_link":""},{"c_code":"200005","itemname":"3P 4TAB","c_pack_code":"","c_web_img_link":""}]
But I need the result as follows
[{"c_code":"2000001","c_code":"200005"},
{"itemname":"303 10CAP","itemname":"3P 4TAB"},
{"c_pack_code":"PK0075","c_pack_code":""},
{"c_web_img_link":"","c_web_img_link":""}]
Example of how you can you make the json from array. Collect the data in two different array and after loop marge them and store the result in another array after that encode them.
Note: Your desired JSON is not a valid format, you can't use same index
for two data.
Online Example: https://3v4l.org/kdPDI
$arr = array(
array(
'c_code' => '200001',
'itemname' => '303 10CAP',
'c_pack_code' => 'PK0075',
'c_web_img_link' => ''
),
array(
'c_code' => '200005',
'itemname' => '3P 4TAB',
'c_pack_code' => '',
'c_web_img_link' => ''
)
);
$res1 = array();
$res2 = array();
foreach($arr as $val){
$res1['c_code'][] = $val['c_code'];
$res1['itemname'][] = $val['itemname'];
$res2['c_pack_code'][] = $val['c_pack_code'];
$res2['c_web_img_link'][] = $val['c_web_img_link'];
}
$out = array(array_merge($res1, $res2));
echo json_encode($out);

PHP: Display data from Array

I working on a program and coming up with some annoying issue. I am trying to display data from an array. I copied the format from another array I setup and it works perfect. The only difference is I am gathering a lot more data...
Calling the function:
$data1 = display_orders($_SESSION['user_id'], $limit, 'fName', 'lName', 'VendorName', 'DateRequested', 'Shipping', 'VendorNumber', 'VendorFax', 'VendorAddress', 'VendorCity', 'VendorState', 'VendorZip', 'EquipmentConsumable', 'GasType', 'GasLocation', 'UNMTag', 'EquipmentLocation', 'index', 'totalcost', 'Approved', 'Shipped');
The Function itself
<?php
function display_orders($user_id, $limit)
{
$data = array();
$user_id = (int)$user_id;
$limit = (int)$limit;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
// print_r($func_get_args);
if ($func_num_args > 1)
{
unset($func_get_args[0]);
unset($func_get_args[1]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
for($x = 0; $x < $limit; $x++)
{
$data[] = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` , `vendor` WHERE $user_id = users.id AND $user_id = vendor.user_id ORDER BY vendor.DateRequested DESC"));
}
return $data;
}
}
?>
So now i try to echo the data out:
echo $data1['VendorName'];
I get no output.
If I do the following:
print_r ($data1);
I get output!
Array ( [0] => Array ( [fName] => admin [lName] => test [VendorName] => Newegg [DateRequested] => 2013-09-19 [Shipping] => Standard [VendorNumber] => NA [VendorFax] => NA [VendorAddress] => NA [VendorCity] => NA [VendorState] => NA [VendorZip] => 00000 [EquipmentConsumable] => Equipment [GasType] => [GasLocation] => [UNMTag] => 0 [EquipmentLocation] => Computer Lab [index] => 0 [totalcost] => 39.99 [Approved] => 0 [Shipped] => 0 ) )
But if i try to add a field name No data....
Any help and I would be grateful!
As you see, $data1 is Array([0] => Array(...)), so you'll need to call
echo $data1[0]['VendorName'];
This is because you are assigning data as $data[] = mysql_fetch_assoc(...).
echo $data1[0]['VendorName'];
I suggest when using print_r you first echo <PRE> as it will help you to see the true structure of the array easier. In this case, the location of VendorName is one layer deeper than you are echoing.
You forgot the index [0]:
echo $data1[0]['VendorName'];

Using a loop to perform multiple SQL inserts using Codeigniter/Activerecord

I have an array that looking like this:
Array
(
[currency] => GBP
[shipping] => 3.5
[tax] => 0
[taxRate] => 0
[itemCount] => 3
[item_name_1] => Proletarian Sparrow
[item_quantity_1] => 2
[item_price_1] => 75
[item_name_2] => Guillemot Colony
[item_quantity_2] => 5
[item_price_2] => 20
[item_name_3] => Dandelion Clock
[item_quantity_3] => 2
[item_price_3] => 50
)
I'm trying to use a loop to extract the individual item details and insert a row in a database for each one. I'm using Codeigniter.
My model looks like this:
public function set_order($cust_id, $order_data)
{
// Breaks up order information and creates a new row in the pn_orders tables for each item
// Get the last row in the orders table so we can work out the next order_id
$this->db->order_by('order_id', 'desc');
$this->db->limit(1);
$query = $this->db->get('pn_orders');
$row = $query->row_array();
// If the resulting array is empty, there are no orders so we can set the order_id to 1. If there is already an order_id, just add 1 to it.
if (empty($row)) {
$order_id = 1;
} else {
$order_id = $row['order_id'] + 1;
}
//echo "<pre>";
//print_r($order_data);
//echo "</pre>";
// The delivery message input has a placeholder. if the user's input is different to this, assign it to $delivery_message.
if ($this->input->post('delivery_message') == "e.g. if out, leave in porch") {
$delivery_message = NULL;
} else {
$delivery_message = $this->input->post('delivery_message');
}
// Set today's date for insertion into the DB
$date = date('Y-m-d');
// The order information is clumped together in a single array. We have to split out single items by looping through the array before inserting them into the DB.
for ($i = 1; $i <= $order_data['itemCount']; $i++) {
$item = array(
'order_id' => $order_id,
'cust_id' => $cust_id,
'date_ordered' => $date,
'item_name' => $order_data["item_name_{$i}"],
'item_quantity' => $order_data["item_quantity_{$i}"],
'item_price' => $order_data["item_price_{$i}"],
'payment_method' => $_POST['payment_method'],
'delivery_message' => $delivery_message
);
$this->db->insert('pn_orders', $item);
}
}
Everything seems to be in place, however, only 1 row is ever inserted and I can't work out why. It seems very simple.
Is it something to do with the Activerecord pattern?
Thanks.
First print out the array to see if the array structure is correct or not. If its Okay then just use insert_batch like this:
for ($i = 1; $i <= $order_data['itemCount']; $i++) {
$items[] = array(
'order_id' => $order_id,
'cust_id' => $cust_id,
'date_ordered' => $date,
'item_name' => $order_data["item_name_{$i}"],
'item_quantity' => $order_data["item_quantity_{$i}"],
'item_price' => $order_data["item_price_{$i}"],
'payment_method' => $_POST['payment_method'],
'delivery_message' => $delivery_message
);
}
//echo "<pre>";print_r($item);echo "</pre>";die; uncomment to see the array structure
$this->db->insert_batch('pn_orders', $items);

Create array of hierarchical directories in PHP

I have the following code (I know that this code is not optimized but it's not for discussion):
function select_categories($cat_id)
{
$this->db = ORM::factory('category')
->where('parent', '=', $cat_id)
->find_all();
foreach ($this->db as $num => $category)
{
if($category->parent == 0)
{
$this->tmp[$category->parent][$category->id] = array();
}
else {
$this->tmp[$category->parent][$category->id] = array();
}
$this->select_categories($category->id);
}
return $this->tmp;
}
Function returns this array:
array(3) (
0 => array(2) (
1 => array(0)
2 => array(0)
)
2 => array(1) (
3 => array(0)
)
3 => array(2) (
4 => array(0)
5 => array(0)
)
)
But how should I change the code
else {
$this->tmp[$category->parent][$category->id] = array();
// ^^^^^^^^^^^^^^^^^^^^^^ (this bit)
}
To merge array[3] to array[2][3] for example (because array[3] is a subdirectory of array[2] and array[2] is a subdirectory of array[0][2]), so, I need to make this (when I don't know the level of subdirectories):
array (
0 => array (
1 => array
2 => array (
3 => array (
4 => array
5 => array
)
)
)
)
A long time ago I wrote some code to do this in PHP. It takes a list of entities (in your case, categories) and returns a structure where those entities are arranged in a tree. However, it uses associative arrays instead of objects; it assumes that the “parent” ID is stored in one of the associative array entries. I’m sure that you can adapt this to your needs.
function make_tree_structure ($nontree, $parent_field)
{
$parent_to_children = array();
$root_elements = array();
foreach ($nontree as $id => $elem) {
if (array_key_exists ($elem[$parent_field], $nontree))
$parent_to_children [ $elem[$parent_field] ][] = $id;
else
$root_elements[] = $id;
}
$result = array();
while (count ($root_elements)) {
$id = array_shift ($root_elements);
$result [ $id ] = make_tree_structure_recurse ($id, $parent_to_children, $nontree);
}
return $result;
}
function make_tree_structure_recurse ($id, &$parent_to_children, &$nontree)
{
$ret = $nontree [ $id ];
if (array_key_exists ($id, $parent_to_children)) {
$list_of_children = $parent_to_children [ $id ];
unset ($parent_to_children[$id]);
while (count ($list_of_children)) {
$child = array_shift ($list_of_children);
$ret['children'][$child] = make_tree_structure_recurse ($child, $parent_to_children, $nontree);
}
}
return $ret;
}
To see what this does, first try running it on a structure like this:
var $data = array (
0 => array('Name' => 'Kenny'),
1 => array('Name' => 'Lilo', 'Parent' => 0),
2 => array('Name' => 'Adrian', 'Parent' => 1)
3 => array('Name' => 'Mark', 'Parent' => 1)
);
var $tree = make_tree_structure($data, 'Parent');
If I’m not mistaken, you should get something like this out: (the “Parent” key would still be there, but I’m leaving it out for clarity)
array (
0 => array('Name' => 'Kenny', 'children' => array (
1 => array('Name' => 'Lilo', 'children' => array (
2 => array('Name' => 'Adrian')
3 => array('Name' => 'Mark')
)
)
)
Examine the code to see how it does this. Once you understand how this works, you can tweak it to work with your particular data.
Assuming you dont want any data/children tags in your array:
foreach ($this->db as $num => $category)
{
// save the data to the array
$this->tmp[$category->id] = array();
// save a reference to this item in the parent array
$this->tmp[$category->parent][$category->id] = &$this->tmp[$category->id];
$this->select_categories($category->id);
}
// the tree is at index $cat_id
return $this->tmp[$cat_id];
If you just need to retrieve the full tree out of the database, you can even simplify your query (get all records at once) and remove the recursive call in this function. You will need an extra check that will only set the $this->tmp[$catagory->id] when it does not exist and else it should merge the data with the existing data.

Categories