SQL to insert data read from excel using PHPExcel - php

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.

Related

Laravel Multiple insert not working says "insert value list does not match "

I have an List which field is dynamic getting by import xlxs. I have generate an array list. Insert work while only xlxs file has 1 record But does not work while getting multiple rows.
When has more than 1 array it says:
SQLSTATE[21S01]: Insert value list does not match column list: 1136
Column count doesn't match value count at row 2
then sql code
My array lists are given below :
Array(
[0] => Array
(
[name] => Md. XXXX
[email] => abc#gmail.com
[mobile_no] => 1751017812
[password] => $2y$10$vgmdsjT64aXHQcPA6vh8LuWfdWWA/NCtC8NLYTl8yyQ/wtXdcSNHy
[user_type_id] => 1
[designation] => Sr. Software Engineer
[market_code] => mirpurA203
[product_code] => Seclo201
[territori_code] => T352
[region_code] => Mirpur334
[division_code] => Dhaka31
)
[1] => Array
(
[name] => Md. XX
[email] => def#gmail.com
[mobile_no] => 1761017812
[password] => $2y$10$52CtpkGrKfriInOmnz.guOrIvnCJyxgYRbfEkDl6nFkPD2UYcvhiO
[user_type_id] => 2
[designation] => Sr. Software Engineer
[territori_code] => T352
[region_code] => Mirpur334
[division_code] => Dhaka31
)
)
I tried with eloquent and DB insert also but it's work while having an only single record.
When inserting multiple items at once, all rows should have the same items. This is because MySQL expects this. An insert query specifies the columns to insert once and expects all the data that follows to match those columns.
INSERT INTO `table` (`col_1`, `col_2`, `col_3`) VALUES (`val_11`, `val_12`, `val_13`), (`val_21`, `val_22`, `val_23`)
Your second object is missing market_code and product_code. Either add these to each record or insert the records separately.

How to take value from First array and generate second array and put the second array in the first array?

I have tried many ways to do this but no luck. I'm trying to take value from First array and generate second array and put the second array in the first array.
The code that I have now, generate the first array, in this array I have column called prereq_id I need to take this value and match it with courses table to bring its information in the courses table course_id=prereq_id. Any help would be highly appreciated
The array output is like this right now
[course_id] => 2
[curriculum_id] => 1
[set_number] => 0
[course_code] => GCIS 516
[course_name] => Data-Centric Concepts and Methods
[credits] => 3
[semester_ava] => 2
[prereq_id] => 10
[set] => 3
php
$result2 = $mysqli->query("SELECT *
FROM curriculumcourses
INNER JOIN courses ON curriculumcourses.course_id = courses.course_id
LEFT JOIN prerequisites ON courses.course_id=prerequisites.course_id
WHERE curriculum_id='$ids' ");
?>
<?php
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result2->fetch_assoc();
}
echo "<pre>";
print_r($rows);
echo "</pre>";
The result I need look like this
[course_id] => 2
[curriculum_id] => 1
[set_number] => 0
[course_code] => GCIS 516
[course_name] => Data-Centric Concepts and Methods
[credits] => 3
[semester_ava] => 2
[prereq_id] => 10
[set] => 3
[course_code] => GCIS 508
[course_name] =>Database Management Systems
[credits] => 3
[semester_ava] => 1

PHP & MySQL, laying out in CSV format with special parameters

I have a database that has budgets in them (for this, I have modified the budgets to be fake).
Long story short, I am attempting to run the following SQL query on the database, and then display a report based on it.
Here is the query: SELECT MONTHNAME(date) AS month, product, SUM(amount) AS spend FROM client_budgets WHERE advertiser_id = '$advertiser_id' GROUP BY MONTHNAME(date), product ORDER BY MONTH(date) ASC
I then clean the data a little, here is the code for that:
foreach($data AS $key => $val) {
$clean_data[] = $val;
}
From this, I get the following (this is a PHP array of the data. I have cut it off since it has about 100K rows in the database currently).
Array
(
[0] => Array
(
[month] => January
[product] => Internet
[spend] => 12000.00
)
[1] => Array
(
[month] => January
[product] => Radio
[spend] => 12250.00
)
[2] => Array
(
[month] => February
[product] => Billboards
[spend] => 6000.00
)
[3] => Array
(
[month] => February
[product] => Internet
[spend] => 16000.00
)
)
My goal is to end up being able to display in a CSV (I already have the headers set for the CSV), the following:
Month, Internet, Radio, Billboards, Television
January, 12000, 12250, 6000, 0
February, 16000, 7000, 6000, 2000
....
I am stuck right now trying to sort the data correctly, and if there is no data for Television for instance one month, to display a 0. Any help would be appreciated! I have been attempting this for almost 3 days now.

Get values from nested stdClass objects, and search sql data type smalldatetime

I'm fairly new to php and sql, and I'm trying to pull a value out of an object or a nested object. I'm able to see the code when i use the print_r command, but i'm unable to separate the actual date from the oject, and I'm also not able to search the sql using the datetime criteria. I do know that the "Date" is stored in sql as a smalldatetime data type, and I don't know how to work with that.
when i try to search sql using the following:
$sql = "SELECT * FROM GL_Register WHERE (Register_Id='5' && Date='2010-12-8 0:00:00')";
I get the following error:
Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '&'. [message] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '&'. ) )
So i cannot pull a query with the date in there properly because i don't know how. to further clarify, i am able to pull information from the database using the following information, but i am still unable to pull out the date from within the Date object.
here's how i'm loading the object:
$sql = "SELECT * FROM GL_Register WHERE Register_Id='3'";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
else{
echo $sql;
}
while($obj = sqlsrv_fetch_object( $stmt)) {
$count++;
$row = '<tr>';
$row .= '<td>'.$count.'</td>';
//$row .= '<td>'.$obj->Date->DateTime->date.'</td>';
$row .= '<td>'.$obj->Account_Id.'</td>';
$row .= '<td>'.$obj->Customer_Id.'</td>';
$row .= '<td>'.$obj->Category_Id.'</td>';
$row .= '<td>'.$obj->Credit_Or_Debit.'</td>';
$row .= '<td>'.$obj->Memo.'</td>';
$row .= '<td>$'.$obj->Amount.'</td>';
$row .= '</tr>';
echo "$row";
}
when i use the "print_r($obj)", this is what it displays:
stdClass Object ( [Register_Id] => 3 [Account_Id] => 5 [Register_Number] => 17 [Credit_Or_Debit] => D [Accounting_Period_Id] => 13 [Date] => DateTime Object ( [date] => 2010-12-21 00:00:00 [timezone_type] => 3 [timezone] => MST ) [Register_Type_Id] => 1 [Reference] => 300002 [Type_CVEO] => C [Customer_Id] => 362 [Vendor_Id] => 1 [Employee_Id] => 1 [Other_Name] => [Offset_Account_Id] => 1 [Splits] => N [Amount] => 179.9600 [Mult_Sign] => 1 [Memo] => Security Services [Status] => O [Is_Offset] => N [Offset_Register_Id] => 4 [Branch_Id] => 2 [Job_Id] => 1 [Service_Ticket_Id] => 1 [Category_Id] => 6 [Job_Expense_Code] => [Expense_Type_Id] => 5 [Post_WIP_Account_Id] => 1 [Primary_Register_Number] => 0 [Part_Id] => 1 [Currency_Id] => 1 [Exchange_Rate] => 1.0000 [Amount_Nat] => 179.9600 [Date_Time_Stamp] => DateTime Object ( [date] => 2010-12-21 12:29:06 [timezone_type] => 3 [timezone] => MST ) )
I need to be able to do two things, and i feel like i'm banging my head against the wall. It's just out of my reach and i'm hoping someone can help me out.
Questions:
How to fix the sql query using the the datetime criteria (ie pull all register_id's that have a date within the last 3 days)?
How to pull the date and time out of the object and place it into a php variable
use AND instead of &&
SELECT * FROM GL_Register WHERE Register_Id='5' AND Date='2010-12-8 0:00:00'
Ok, so with the help of a friend and chetan above, i was able to answer the first question. my first problem was that i had the wrong operators in the question. my second problem, was i was formatting the date wrong. the date needed to be formatted one of the following two ways:
select * from GL_Register where Date = '07/01/2013'
or
select * from GL_Register where Date = {d'2013-07-01'}
The first method uses an implicit conversion from varchar to date. The order of the date IE 'mm/dd/yyyy' or 'dd/mm/yyyy' is controlled by your local settings.The second method is more proper as the {d} specifies that the varchar is to be converted to a date and is not dependent on your date format settings.
but i still need the answer to the second question, how do i print the date out on a datetime object?
answered the second question. since the sql was outputting data in the DateTime format, i needed to create a new DateTime variable and dump the information into that object. once i did that, i was able to format the data ho i needed to and use it accordingly.
$newDate = new DateTime('NOW');
while($obj = sqlsrv_fetch_object($stmt)) {
$newDate = $obj->Date->format('Y-m-d');
This outputs the date in the format i need.

Get meta information for selected columns from PostgreSQL using PHP

is there a way of getting table name for each column in a postgre result in PHP?
Imagine you have a select with join, for example:
$Q = <<<E2OD
SELECT * FROM user U
LEFT JOIN department D ON U.department_id = D.id
E2OD;
In PHP/FirebirdSQL:
$R = ibase_query($Q);
$D = ibase_fetch_row($R);
$info = ibase_field_info($R, 0);
Returns
Array
(
[0] => id
[name] => id
[1] => id
[alias] => id
[2] => user
[relation] => user
[3] => 8
[length] => 8
[4] => BIGINT
[type] => BIGINT
)
While in PHP/PostgreSQL:
$select = $DB->query($Q);
$meta = $select->getColumnMeta(0);
Returns
Array
(
[pgsql:oid] => 20
[native_type] => int8
[name] => id
[len] => 8
[precision] => -1
[pdo_type] => 2
)
As you see, there's no information about the table the column is from. There's a missing key [relation] => user or similar displaying the table name.
http://php.net/manual/en/pdostatement.getcolumnmeta.php
Can PHP get this information with it's PG or PDO libraries? Does PostgreSQL provide this information to client libraries? What needs to be done to make this happen?
Thanks for any hint,
Michal
Check pg_field_table().

Categories