Creating booking overview (table) from MySQL Database - Combining arrays - php

I am desperate because of my lack of programming experience.
I am working on a small WordPress plugin, a room booking system.
Now my problem is to create the daily overview.
In the database, there is a table with all bookings looking like this:
--------------------------------------------------------------
|id|user_id| starttime | endtime |room|type|
---+-------+-------------------+-------------------+----+-----
|1 | 101|2017-08-24 11:00:00|2017-08-24 12:30:00|12 | 4 |
|2 | ...
The overview / calendar / schedule for every day should be made as an HTML-Table using Bootstrap and look like the following:
Time Conference Room Meeting Room Lobby
07:00 Mr. T
08:00 Mr. T
09:00 C.J.P. Mrs. L.
10:00
11:00
12:00 Mrs. M
So the free timeslots should be empty columns.
To achieve this, I started using a function to create all starttimes:
$times_array = array();
$timing_interval = get_option('timing');
for ($hours = get_option('starttime'); $hours < get_option('endtime'); $hours++) {
for ($m = 0; $m < 60; $m += $timing_interval) {
$starttime_html = sprintf('%02u:%02u', $hours, $m);
$times_array[$starttime_html]='';
}
}
Afterwards I created an array containing the already saved bookings:
$booking_array = array();
$statement = $wpdb->get_results( $wpdb->prepare("SELECT {$mpbs_prefix}_bookings.id, user_id, wp_users.user_nicename AS username_nice, starttime, facility_id, roomname, equipment_1, {$mpbs_prefix}_equipment.name AS eq_1_name, equipment_2 FROM {$mpbs_prefix}_bookings, {$mpbs_prefix}_facilities, {$mpbs_prefix}_equipment, wp_users WHERE user_id = wp_users.ID AND equipment_1 = {$mpbs_prefix}_equipment.id AND {$mpbs_prefix}_facilities.id = {$mpbs_prefix}_bookings.facility_id AND starttime >= '2017-08-22 00:00:00'"),ARRAY_A);
$bookingrow = 0;
foreach($statement as $actualbookings) {
$starttime_currentday = explode(" ",$statement[$bookingrow]['starttime']);
$starttime_curr_hm = substr($starttime_currentday[1],0,5);
$booking_array[$bookingrow] =
array('starttime_of_booking'=>$starttime_curr_hm, 'facliId'=>$statement[$bookingrow]['facility_id'],'userid'=> $statement[$bookingrow]['username_nice'], 'horse_1_name' => $statement[$bookingrow]['horse_1_name']);
$bookingrow++;
}
As there are a lot of rooms (facilities) in different categories, I chose a tabbed navigation from Bootstrap.
Therefore I created a function to "draw" the table using information from three directions:
The column heads directly from the database
the starting times created in PHP (see above)
the already booked times and facilities saved in my $booking_array
As the HTML-table is created row wise, I thought it would be a good approach to check if the starttime is also available in the $booking_array and if yes to add a cell containing the username.
So far that worked, but now I wanted to have all free slots as empty cells. So I tried a lot but always end up in a table with hundreds of empty rows.
In my last approach I used a function I found here, to check if the starttime is not in my multidimensional associative array ($booking_array) and to add the empty cell:
$drawTable = function($funcFormCat, $funcFacId) use ($mpbs_overview_category_query, $times_array, $booking_array) {
echo "<table class='table table-hover'>";
echo "<thead>";
//echo "<th class='text-center'></th>";
foreach ($mpbs_overview_category_query as $overview_formcategories) {
if ($overview_formcategories->formcategory == $funcFormCat && $overview_formcategories->facility_id == $funcFacId) {
echo "<th class='text-center' id='$overview_formcategories->facility_id'>" . $overview_formcategories->facility ."</th>";
}
}
echo "</thead>";
foreach ($times_array as $timeskey => $timesvalue) {
echo "<tr>";
// echo "<td class='text-center'>.</td>";
for ($booking_array_id = 0; $booking_array_id < count($booking_array); $booking_array_id++ ) {
if ($booking_array[$booking_array_id]['starttime_of_booking'] == $timeskey && $booking_array[$booking_array_id]['facliId'] == $funcFacId ) {
echo "<td class='text-center'>" . $booking_array[$booking_array_id]['username'] . "</td>";
echo "</tr>";
}
elseif (in_array_r($timeskey, $booking_array)==false) {
echo "<td class='text-center'>**</td>";
echo "</tr>";
}
}
}
My arrays do contain the following format:
$times_array
Array ( [07:00] => [07:30] => [08:00] => [08:30] => [09:00] => [09:30] => [10:00] => [10:30] => [11:00] => [11:30] => [12:00] => [12:30] => [13:00] => [13:30] => [14:00] => [14:30] => [15:00] => [15:30] => [16:00] => [16:30] => [17:00] => [17:30] => [18:00] => [18:30] => [19:00] => [19:30] => [20:00] => [20:30] => [21:00] => [21:30] => )
$booking_array
Array ( [0] => Array ( [starttime_of_booking] => 08:00 [facliId] => 6 [userid] => Mr T [equipment] => Beamer ) [1] => Array ( [starttime_of_booking] => 14:00 [facliId] => 4 [userid] => Mrs. L [equipment] => Flipchart ) [2] => Array ( [starttime_of_booking] => 14:00 [facliId] => 9 [userid] => Mrs. M [equipment] => TV-Set ) [3] => Array ( [starttime_of_booking] => 13:00 [facliId] => 8 [userid] => C.J.P. [equipment] => Stuff )
As I am trying around for hours now and do not get a correct overview, I would be very happy for any hints, tips or suggestions!
Thanks in advance.
Regards
Lars
To clarify, what I want to achieve, I add some more information here:
What I want is to create a HTML-Table, which is populated from the 3 sources:
At first he table's heading should be made by a SQL-query to get the room names and their ids. (<thead><th id='facility_id'>room1</th><th id='facility_id'>room2</th id='facility_id'>...</thead>
Afterwards in the 1st data row in the 1st column the 1st starttime coming from $times_array should be printed. ("<td>".$timeskey."</td>").
All remaining cells should also be formatted as HTML-Cells.
Now comes the tricky part (for me), as I want to populate those cells, where already a booking was made.
For example the conference room is booked from 07:00 to 09:00 by Mr.T.
To achieve this without Ajax, I created the array $booking_array with the data from my bookings database table.
Now I am stuck on writing a function, which draws my HTML-Table with all necessary information at the right place.
A <tr> tag is printed to open a new row. In the next step a cell with the starttime is added. And now I want to iterate through my $bookings_array for any booking starting at this time and printing the username to the corresponding column.
As I did not get that to work, in one table, I tried to achieve it by creating a single table for each room containing the starttimes and the column with the booking data / free slots. But the table gets hundreds of rows.

Related

How do we calculate monthly sale in codeigniter?

I have trouble with some calculation in Codeigniter. Please check attached image below
https://imgur.com/HuSBkXJ
That data fetching from the database , the sale column is fine but I having trouble with monthly sale
1st day of every month sale (10) and monthly sale (10) are same, but from second day sale is correct(8), monthly sale has to be 1st day sale + second day sale(10+8 = 18). for third day sale is fine, monthly sale should be (18+20=38). the calculation going like this up to end of the month, Same process again stating from next month
How do we calculate in codeigniter, The above image i have created in excel sheet for demonstration purpose.
Model view
public function fetchSaleData()
{
$this->db->join('stock_shop','stock_shop.shop_id = stock_sale.shopId');
$this->db->join('stock_products','stock_products.product_id = stock_sale.productID');
$thisMonth=date('m');
$this->db->where('MONTH(DateOfSale)',$thisMonth);
$query= $this->db->get("stock_sale");
return $query->result_array();
}
controller view
public function salesView()
{
$data['sales']=$this->Query_sale->fetchSaleData();
$data['shops']=$this->Query_sale->fetchShop();
$this->load->view('stock/shop_sales_view',$data);
}
since you're not showing table structures or any other insight, I'll only suggest an approach based on my own code which you may feel free to adapt to your specific needs, along with the assumptions I make along the way
Assumption #1: the model returns an array in which each element contains the date and the sold units on such date
This would look like this
+-----------------+
| array data |
+------------+----+
| 2020-01-01 | 10 |
+------------+----+
| 2020-01-02 | 20 |
+------------+----+
| 2020-01-03 | 5 |
+------------+----+
| 2020-01-04 | 8 |
+------------+----+
On array form, this may look like this:
$ar = array(
0 => array(
'date' => '2020-01-01',
'units_sold' => 10,
),
1 => array(
'date' => '2020-01-02',
'units_sold' => 20,
),
2 => array(
'date' => '2020-01-03',
'units_sold' => 5,
),
3 => array(
'date' => '2020-01-04',
'units_sold' => 8,
),
);
and so on until the end of the month. Lets call the returned fields date and units_sold as in the above example
now that you have the data loaded in a variable ($ar) you can loop through it and keep tabs on the accumulated total on each loop.
$accum = 0; // keep track of accumulated total
$i = 0; // keep track of array index
foreach ($ar as $a)
{
$accum += $a['sales'];
$ar[$i]['accum'] = $accum;
$i++;
}
Upon running, this code will:
Iteration 0: For 2020-01-01, sales=10, accumulated=10
Iteration 1: For 2020-01-02, sales 20, accumulated=30
Iteration 2: For 2020-01-03, sales 5, accumulated=35
...and so on until the month is over
The above can be verified with a print_r or var_dump (I use print_r... like this: print print_r($ar,true);):
print_r output
Array
(
[0] => Array
(
[date] => 2020-01-01
[sales] => 10
[accum] => 10
)
[1] => Array
(
[date] => 2020-01-02
[sales] => 20
[accum] => 30
)
[2] => Array
(
[date] => 2020-01-03
[sales] => 5
[accum] => 35
)
[3] => Array
(
[date] => 2020-01-04
[sales] => 8
[accum] => 43
)
)
So, now that you've succesfully pushed a whole new element in your result array, you can send it over to the view and display it in tabular form as you need

How to append a serialized string that already exists in the database

I have just started to learn about serialization and I have a question that I cannot seem to find a simple explanation to.
Say I had a table called week and inside week I had 3 columns with the third column containing a bunch of serialized meal IDs like so stored in my database:
INSERT INTO `week` (`week_id`, `meal_code`, `meal_id`) VALUES
(1, 'week12016', 'a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}');
But later I want to append another meal_id to the existing string but not update any other column so it reads
(1, 'week12016','a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}')
I have tried in a php file to store the following
$food=array("7");
$sfood=serialize($food);
Then trying to add the 7 to the existing meal_ids in the week table
mysqli_query($conn,"UPDATE week
SET meal_id ('$sfood')");
//if entry into the database is successful, confirm with a alert popup and refresh the home page
if(mysqli_affected_rows($conn) > 0){
//header("location: admin.php");
header("refresh:0; url=admin.php");
echo "<script type='text/javascript'>alert('Upload Successful!')</script>";
exit;
But when I check my database, nothing has changed.
What am I doing wrong, is it even possible to do what I am trying to achieve?
You have to read the column from your table row. Unserialize it into a PHP variable and then add a new occurance to it.
Then serialize the new array and store it back to your database
// SELECT from table
$s = 'a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}';
$d = unserialize($s);
print_r($d);
$d[] = 99;
print_r($d);
$s2 = serialize($d);
echo $s2;
// UPDATE table row
RESULTS
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 99
)
a:8:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;i:7;i:99;}
Storing data like this is not recommended, as it makes this data impossible to process using queries

How can I return mysql search results where only the columns with non-null entries are displayed

I am having trouble trying to output a mysql search in the way that I want. I cannot find an answer to my specific question anywhere yet with lots of searching and am hoping someone on this forum would be willing to help! I see it logically as a two step process.
First, I want to execute a mysql search where the search criteria selects for table rows where a specific column has data:
SELECT *
FROM `mytable`
WHERE column3 = 'yes'
This gives a subset of my table with only the rows containing 'yes' in column3.
Now, for the second step I would like to remove all columns from this subset table that do not contain any information (i.e., are null). I'm sure this is easy for a pro, but trying to cut the 'null columns' is stumping me and does not seem to be answered online yet. Your help would be greatly appreciated!
SELECT * FROM mytable WHERE column3 IS NOT NULL;
or what do you mean something like this?
SELECT * FROM mytable WHERE column3 = 'yes' AND column1 IS NOT NULL;
After further digging, I have finally come to realize that while you can easily filter for certain rows of data using mysql, filtering for certain columns of data dynamically is a different matter. I had assumed that columns could be filtered like rows. I found an answer to a similar question by bluish in 2011 that describes this: https://stackoverflow.com/a/4748682/5033595
Now that I understand the concept better, I still need more information to construct the code that will accomplish what is described by bluish in the link. I will edit this answer if I come up with this myself. Conversely, I would appreciate it if anyone else would be willing to contribute an answer with the code.
Ok, sorry for the delay and thanks to everyone for your advice. After sleuthing the internet forums and trying different options, I finally discovered a solution. In this solution, the key is using array_filter() to identify if data is contained in an array, or if it is empty. This works for 1-dimensionnal arrays, so I first moved every column of mysql data into its own 1-dimensionnal array and used the array_filter() as a tool to decide which columns will be published in the HTML table. The code and output follows. Enjoy...
CODE>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php
//STEP 1: Making and confirming a connection to the Database>>>>>>>>>>>>>>>>>>>>>>>>>>
echo "STEP 1: MAKING A CONNECTION TO THE MYSQL DATABASE...<BR><BR>";
//make connection
$db = mysql_connect("localhost","root","urpassword");
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
} echo "Connected successfully<BR>";
//select database
$db_select = mysql_select_db("mydatabase",$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
} echo "Database selected successfully<BR>";
//query
$result = mysql_query("SELECT * FROM employees2", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
} echo "Database queried successfully<BR>";
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//STEP 2 OUTPUTTING THE MYSQL SEARCH OF THE WHOLE DATABASE INCLUDING EMPTY COLUMN>>>>>>>>>>>>>>>>>>>>>>>>>>>>
?>
<HTML>
<HEAD>
<TITLE>Only showing table columns containing data</TITLE>
</HEAD>
<BODY>
<BR><p>STEP 2: PLACING THE MYSQL TABLE INTO AN HTML TABLE</P><BR>
<TABLE width="600" border="1" cellpadding="1" cellspacing="1">
<TR>
<TH>Name</TH>
<TH>Age</TH>
<TH>Position</TH>
<TH>Height</TH>
<TH>Salary</TH>
</TR>
<?php
while ($row=mysql_fetch_assoc($result)) {
echo "<TR>";
echo "<TD>".$row['Name']."</TD>";
echo "<TD>".$row['Age']."</TD>";
echo "<TD>".$row['Position']."</TD>";
echo "<TD>".$row['Height']."</TD>";
echo "<TD>".$row['Salary']."</TD>";
echo "</TR>";
} //end while
?>
</TABLE>
<!-- <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< -->
<?PHP
//STEP 3 Put mysql database into 2 dimension array: I didn't know my mysql >search wasn't in an array format already!!>>>>>>>>>>>>>
echo "<BR><BR>STEP 3: CONVERTING THE MYSQL TABLE INTO A 2-DIMENSIONNAL ARRAY<BR><BR>";
$query = mysql_query("SELECT * FROM employees2", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
}
print_r($results);
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//STEP 4 - Fetching each column as its own array>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
echo "<BR><BR><BR>STEP 4: FETCHING EACH ARRAY COLUMN AS ITS OWN ARRAY";
$query = mysql_query("SELECT * FROM employees2", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Age = array_column($results, 'Age');
$Position = array_column($results, 'Position');
$Height = array_column($results, 'Height');
$Salary = array_column($results, 'Salary');
}
echo "<BR><BR>";
print_r($Name);
echo "<br>";
print_r($Age);
echo "<br>";
print_r($Position);
echo "<br>";
print_r($Height);
echo "<br>";
print_r($Salary);
echo "<br>";
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//STEP 5 - Identifying if individual column arrays contain data>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
echo "<BR><BR>STEP 5: CONFIRMING THAT YOU CAN IDENTIFY IF A COLUMN SEPARATED INTO ITS OWN ARRAY IS EMPTY<BR><BR>";
$query = mysql_query("SELECT * FROM employees2", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Age = array_column($results, 'Age');
$Position = array_column($results, 'Position');
$Height = array_column($results, 'Height');
$Salary = array_column($results, 'Salary');
}
if(array_filter($Name)) {
echo "contains at least one non-empty element<BR>";} else echo "is empty<BR>";
if(array_filter($Age)) {
echo "contains at least one non-empty element<BR>";} else echo "is empty<BR>";
if(array_filter($Position)) {
echo "contains at least one non-empty element<BR>";} else echo "is empty<BR>";
if(array_filter($Height)) {
echo "contains at least one non-empty element<BR>";} else echo "is empty<BR>";
if(array_filter($Salary)) {
echo "contains at least one non-empty element<BR>";} else echo "is empty<BR>";
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
?>
<!-- STEP 6 - Creating table that only displays columns with data>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> -->
<BR><p>STEP 6: CREATING AN HTML TABLE THAT ONLY DISPLAYS COLUMNS WITH DATA</P><BR>
<TABLE width="500" border="1" cellpadding="1" cellspacing="1">
<?php
$query = mysql_query("SELECT * FROM employees2", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Age = array_column($results, 'Age');
$Position = array_column($results, 'Position');
$Height = array_column($results, 'Height');
$Salary = array_column($results, 'Salary');
}
echo "<TR>";
if(array_filter($Name)) {echo "<TH>Name</TH>";}
if(array_filter($Age)){echo "<TH>Age</TH>";}
if(array_filter($Position)){echo "<TH>Position</TH>";}
if(array_filter($Height)){echo "<TH>Height</TH>";}
if(array_filter($Salary)){echo "<TH>Salary</TH>";}
echo "</TR>";
$query = mysql_query("SELECT * FROM employees2", $db);
while($line = mysql_fetch_assoc($query)){
echo "<TR>";
if(array_filter($Name)) {echo "<TD>".$line['Name']."</TD>";}
if(array_filter($Age)) {echo "<TD>".$line['Age']."</TD>";}
if(array_filter($Position)) {echo "<TD>".$line['Position']."</TD>";}
if(array_filter($Height)) {echo "<TD>".$line['Height']."</TD>";}
if(array_filter($Salary)) {echo "<TD>".$line['Salary']."</TD>";}
echo "</TR>";
}
?>
</TABLE>
<BR><BR><BR><BR>
</BODY>
</HTML>
<?php
//closing mysql database
mysql_close($db);
?>
CODE<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
OUTPUT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
STEP 1: MAKING A CONNECTION TO THE MYSQL DATABASE...
Connected successfully
Database selected successfully
Database queried successfully
STEP 2: PLACING THE MYSQL TABLE INTO AN HTML TABLE
Name Age Position Height Salary
Chris Mogan 25 Assistant Programmer 170000
Emily Grant 25 Accountant 120000
James Daniel 27 Lead Programmer 210000
Jessica Pam 28 Group Head 250000
Mike Pablo 23 Head Designer 200000
Nick Meyers 24 Assistant Designer 150000
STEP 3: CONVERTING THE MYSQL TABLE INTO A 2-DIMENSIONNAL ARRAY
Array ( [0] => Array ( [Name] => Chris Mogan [Age] => 25 [Position] => Assistant Programmer [Height] => [Salary] => 170000 ) [1] => Array ( [Name] => Emily Grant [Age] => 25 [Position] => Accountant [Height] => [Salary] => 120000 ) [2] => Array ( [Name] => James Daniel [Age] => 27 [Position] => Lead Programmer [Height] => [Salary] => 210000 ) [3] => Array ( [Name] => Jessica Pam [Age] => 28 [Position] => Group Head [Height] => [Salary] => 250000 ) [4] => Array ( [Name] => Mike Pablo [Age] => 23 [Position] => Head Designer [Height] => [Salary] => 200000 ) [5] => Array ( [Name] => Nick Meyers [Age] => 24 [Position] => Assistant Designer [Height] => [Salary] => 150000 ) )
STEP 4: FETCHING EACH ARRAY COLUMN AS ITS OWN ARRAY
Array ( [0] => Chris Mogan [1] => Emily Grant [2] => James Daniel [3] => Jessica Pam [4] => Mike Pablo [5] => Nick Meyers )
Array ( [0] => 25 [1] => 25 [2] => 27 [3] => 28 [4] => 23 [5] => 24 )
Array ( [0] => Assistant Programmer [1] => Accountant [2] => Lead Programmer [3] => Group Head [4] => Head Designer [5] => Assistant Designer )
Array ( [0] => [1] => [2] => [3] => [4] => [5] => )
Array ( [0] => 170000 [1] => 120000 [2] => 210000 [3] => 250000 [4] => 200000 [5] => 150000 )
STEP 5: CONFIRMING THAT YOU CAN IDENTIFY IF A COLUMN SEPARATED INTO ITS OWN ARRAY IS EMPTY
contains at least one non-empty element
contains at least one non-empty element
contains at least one non-empty element
is empty
contains at least one non-empty element
STEP 6: CREATING AN HTML TABLE THAT ONLY DISPLAYS COLUMNS WITH DATA
Name Age Position Salary
Chris Mogan 25 Assistant Programmer 170000
Emily Grant 25 Accountant 120000
James Daniel 27 Lead Programmer 210000
Jessica Pam 28 Group Head 250000
Mike Pablo 23 Head Designer 200000
Nick Meyers 24 Assistant Designer 150000
OUTPUT<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

PHP - Create a Schedule table in relation to time

I'm doing a school project and I have to create a schedule from an array. I already sorted the array by day & time. I know how to create a simple table and insert the data - but I wanted to make a more defined table in relation to time:
The array for Monday looks like this:
Array ( [0] => Array ( [courseID] => comp275 [lectureID] => gg [day] => monday [stime] => 12:15 [etime] => 15:16 [term] => winter [year] => 2014 ) [1] => Array ( [courseID] => comp345 [lectureID] => ss [day] => monday [stime] => 18:20 [etime] => 20:30 [term] => winter [year] => 2014 ) )
I want the table to be like this for column "Monday"
table type http://4.ii.gl/mtHVQN.png
This is my code at the moment (its a bit broken but i haven't figured out how to do what i really want yet.)
<table>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
<?php getMonday($Array); ?>
</table>
Function :
foreach($Array as $MA)
{
echo
"<tr class='success'><td>".
"Start-Time :".$MA["stime"]." "
."<br><br>".
"Course :".$MA["courseID"]." "
."<br><br>".
"End-Time :".$MA["etime"]." "
."</td></tr>";
}
Gives me this :
table type2 http://2.ii.gl/Q1Dx-x.png
Instead of using cells in your day colum, you could create divs for each class and change the height based off the time. For example -
$curr_time = strtotime('08:00'); //beginning of the day
foreach($Array as $MA) {
// create a blank div if it does not equal $curr_time
if(strtotime($MA['stime']) != $curr_time){
$empty_size = // get size for difference between $MA['stime'] and $curr_time
echo "<div style='height:{$empty_size}px;'></div>";
}
// create the div for the class time
$div_size = // get size for difference between $MA['etime'] and $MA['stime']
echo "<div class='success' style='height:{$div_size}px;'>".
// your data
"Start-Time :".$MA["stime"]." "
."<br><br>".
"Course :".$MA["courseID"]." "
."<br><br>".
"End-Time :".$MA["etime"].
// end of your data
"</div>";
// change the $curr_time to $MA['etime']
$curr_time = strtotime($MA['etime']) ;
}
since this is a school project, I won't give you all the code / full working example, just this sample code/idea. You would need to find a way to determine the height of the divs based off the difference in time. Hopefully this helps.

SQL to insert data read from excel using PHPExcel

I am currently working on reading a excel using php and storing those records in mysql.I came across PHPExcel,a bunch of very nice plugin classes which can very easily help to achive it.I tried to search through but did not something similar to my use case.Also,not very good at object oriented PHP and I am short of time in doing this.
First Name Last Name Nationality Gender Date of Birth Time of Birth Date/Time PHP Coder Sanity %Age
Above are my sample database columns and First row of my excel sheet.I want to match the column names of my rows before inserting them to database.
My code till now gives me a 2 dimensional array in which I get the column names and values.The reason I want to check the column name before inserting is that,my excels can be in any order of the column names.
I used exampleReader01 in the package and some SO reference to achieve this.
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading){
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
Now I want some help how can I insert this in the right column.
My array is like this
Array
(
[0] => Array
(
[First Name] => Mark
[Last Name] => Baker
[Nationality] => British
[Gender] => M
[Date of Birth] => 19-Dec-60
[Time of Birth] => 1:30
[Date/Time] => 22269.0625
[PHP Coder] => 1
[Sanity %Age] => 32%
)
[1] => Array
(
[First Name] => Toni
[Last Name] => Baker
[Nationality] => British
[Gender] => F
[Date of Birth] => 24-Nov-50
[Time of Birth] => 20:00
[Date/Time] => 18591.83333
[PHP Coder] =>
[Sanity %Age] => 95%
)
[2] => Array
(
[First Name] => Rachel
[Last Name] => Baker
[Nationality] => British
[Gender] => F
[Date of Birth] => 7-Dec-82
[Time of Birth] => 0:15
[Date/Time] => 30292.01042
[PHP Coder] =>
[Sanity %Age] => 100%
)
)
Hope I am clear.
Thanks for your time.
If I can assume that your Excel column header names never change, why not simply use a mapping array?
$dbMapping = array(
'col1' => header1,
'col2' => header2,
..
'colN' => headerN
);
So when you're ready to insert to the database, you iterate through each row with the column header names you already have in your 2D array and pass it into your mapping array i.e. $dbMapping['col1'] and that will get you your header name and you can grab the correct row value.
psuedo
foreach ($rows as $row) {
insert into col1, col2, ... colN
values ($rows[$dbMapping['col1']], $rows[$dbMapping['col2']], ...
}
Of course it would be in your best interest to use parameterized values.

Categories