Интеграция базы данных MySQL с WORD

Для Word используются файлы с расширением.docx, которые есть ничто иное как обычный zip-архив, поэтому решение напрашивается само собой: класс-генератор документов должен быть наследником класса ZipArchive, который доступен «из коробки». А остальное — дело техники. Для работы с MSWordиспользовалась библиотека PHPWord. Файлы формировались с помощью кода через стили, а также при помощи шаблонов.

 

require_once ('lib/PHPWord.php');

$controller = explode('/', $_GET['route']);

if (!isset($controller[1]) || strlen($controller[1]) == 0)

{die();}

$sectionID = intval(trim(strip_tags($controller[1])));

$sectionClass = new Section($sectionID,$db);

if (!$sectionClass->isIsset ())

{die();}

$sectionFacultyData = $sectionClass->getFacultySection();

$comision = new Commission($sectionID,$db);

 

$comisData = $comision->getCommision();

$report = new Report($sectionID,$db);

$positions = $sectionClass->getArrayPositions();

$fasc = $sectionClass->getArrayFaculties();

$courses = $sectionClass->getArrayCourses();

$uid = md5(uniqid(rand(), true));

$sectionData = $sectionClass->getDataSection ();

$dateArr = explode(':', $sectionData['time']);

$sectionData['time'] = $dateArr[0].":".$dateArr[1];

$stmt = $db->dbStream->prepare("SELECT `place`, COUNT(`place`)

FROM `reports`

 

WHERE `reports`.`id_section` =? GROUP BY `place`");

$stmt->bindValue(1, $sectionID, PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$countM = $stmt->fetchAll(PDO::FETCH_ASSOC);

$countmesta = 0;

$count = 0;

foreach ($countM as $key => $value)

{

$countmesta =($value['place']!= 0)? $countmesta + $value['COUNT(`place`)']: $countmesta;

$count += $value['COUNT(`place`)'];

}

if ($countmesta > ceil($count*0.4))

{

$answer = ['code' => '2',];

echo(json_encode($answer));

die();

}

$stmt = $db->dbStream->prepare("SELECT

`reports`.`ID` AS `ID_REPORT`,

`speakers`.`ID` AS `ID_SPEAKER`,

`speakers`.`id_position`,

`reports`.`id_section`,

`reports`.`name_report`,

`reports`.`place`,

IFNULL(`speakers`.`id_report`,0) AS `id_report`,

IFNULL(`speakers`.`fio`,0) AS `fio`,

IFNULL(`speakers`.`type`,0) AS `type`

FROM `reports`

LEFT JOIN `speakers`

ON `reports`.`ID` =`speakers`.`id_report`

WHERE `reports`.`id_section` =?

ORDER BY `reports`.`place` ");

$stmt->bindValue(1, $sectionID, PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$people = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*

* Считаем количество

*/

$stmt = $db->dbStream->prepare("SELECT `meta_key`,`meta_value` FROM `count_people` WHERE `id_section` =?");

$stmt->bindValue(1, $sectionID, PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$comisCount = $stmt->fetchAll(PDO::FETCH_ASSOC);

$arrayCOUNT = array();

foreach ($comisCount as $countkey)

{

if (!isset($arrayCOUNT[$countkey['meta_key']]))

{

$arrayCOUNT[$countkey['meta_key']] = intval($countkey['meta_value']);

} else

{

$arrayCOUNT[$countkey['meta_key']] += $countkey['meta_value'];

}

}

/*

* Считаем количество коммисии

*/

$stmt = $db->dbStream->prepare("SELECT `id_position`, COUNT(`id_position`) FROM `commission` WHERE `id_section` =? GROUP BY `id_position`");

$stmt->bindValue(1, $sectionID, PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$comisCount = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($comisCount as $countkey)

{

if (!isset($arrayCOUNT[$countkey['id_position']]))

{

$arrayCOUNT[$countkey['id_position']] = intval($countkey['COUNT(`id_position`)']);

} else

{

$arrayCOUNT[$countkey['id_position']] += $countkey['COUNT(`id_position`)'];

}

}

/*

* Считаем количество докладчиков

*/

foreach ($peopleas $user)

{

if (!isset($arrayCOUNT[$user['id_position']]))

{

$arrayCOUNT[$user['id_position']] = 1;

} else

{

$arrayCOUNT[$user['id_position']]++;

}

 

}

$count = 0;

foreach ($arrayCOUNT as $arrayC)

{

$count += $arrayC;

}

 

 

$PHPWord = new PHPWord();

 

// New portrait section

$section = $PHPWord->createSection();

$PHPWord->setDefaultFontName('Times New Roman');

$PHPWord->setDefaultFontSize(12);

// Add text elements

$PHPWord->addFontStyle('facultyStyle', array('bold'=>true, 'size'=>12));

$PHPWord->addFontStyle('textFontStyle', array('size'=>12));

$PHPWord->addFontStyle('italicStyle', array('bold'=>true, 'italic'=>true, 'size'=>12));

$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));

$section->addText($sectionFacultyData['full_name'],'facultyStyle', 'pStyle');

$section->addText('ПРОТОКОЛ','textFontStyle', 'pStyle');

$section->addText('заседания Регионального фестиваля студентов и молодёжи «Человек. Гражданин. Учёный» (ЧГУ-2017) от 14 ноября 2017 года','textFontStyle', 'pStyle');

$section->addText("Секция «".$sectionData['name']."»", 'facultyStyle', 'pStyle');//underline

$section->addText('ауд. '.$sectionData['cabinet'].', '.$sectionData['date'].' начало в '.$sectionData['time'], 'facultyStyle', 'pStyle');

$section->addTextBreak(1);

// Define table style arrays

$styleTable = array('borderSize'=>6, 'borderColor'=>'000000', 'cellMargin'=>80);

$styleFirstRow = array('borderBottomSize'=>6, 'borderBottomColor'=>'000000', 'bgColor'=>'FFFFFF');

 

// Define cell style arrays

$styleCell = array('valign'=>'center');

$styleCellBTLR = array('valign'=>'center', 'textDirection'=>PHPWord_Style_Cell::TEXT_DIR_BTLR);

 

// Define font style for first row

$fontStyle = array('align'=>'left');

$italicStyle = array('italic'=>true, 'align'=>'center');

 

 

// Add table style

$PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);

 

// Add table

$table = $section->addTable('myOwnTableStyle');

 

// Add row

$table->addRow();

 

// Add cells

$table->addCell(3000, $styleCell)->addText('Состав комиссии', $italicStyle);

$table->addCell(4000, $styleCell)->addText('Ф.И.О.', $italicStyle);

$table->addCell(3000, $styleCell)->addText('Должность', $italicStyle);

// Add more rows / cells

for($i = 1; $i <= count($comisData); $i++) {

$table->addRow();

if($comisData[$i-1]['id_status'] == 1)

{

$table->addCell(3000)->addText('Председатель секции', $italicStyle);

 

} elseif($comisData[$i-1]['id_status'] == 2)

{

$table->addCell(3000)->addText('Секретарь секции', $italicStyle);

} else

{

$table->addCell(3000)->addText('Другие члены жюри', $italicStyle);

}

$table->addCell(4000)->addText($comisData[$i-1]['fio']);

$table->addCell(3000)->addText($comisData[$i-1]['name']);

}

$section->addTextBreak(1);

$PHPWord->addParagraphStyle('textStyle', array('align'=>'left', 'spaceAfter'=>100));

$section->addText('Присутствовали (количество):'.$count.' чел.', null, 'textStyle');

$section->addText('Из них (указать в числах):', null, 'textStyle');

foreach ($positions as $position)

{

if (isset($arrayCOUNT[$position['ID']]) && $arrayCOUNT[$position['ID']] > 0)

{

$section->addText($arrayCOUNT[$position['ID']].' '.$main->num2word($arrayCOUNT[$position['ID']], [(strtolower($position['name'])), $position['name_2'], $position['name_3']]), null, 'textStyle');

}

}

 

$section = $PHPWord->createSection();

$section->addText('I. ВЫСТУПИЛИ:', null, 'textStyle');

// Add table style

$PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);

// Add table

$table = $section->addTable('myOwnTableStyle');

$table->addRow();

$table->addCell(200, $styleCell)->addText('№ п/п', $italicStyle);

$table->addCell(3000, $styleCell)->addText('Ф.И.О. докладчика', $italicStyle);

$table->addCell(1500, $styleCell)->addText('Группа', $italicStyle);

$table->addCell(2000, $styleCell)->addText('Название доклада', $italicStyle);

$table->addCell(3000, $styleCell)->addText('Ф.И.О. и должность научного руководителя', $italicStyle);

$index = 1;

$stmt = $db->dbStream->prepare("SELECT * FROM `reports` WHERE `id_section` =?");

$stmt->bindValue(1, $sectionID, PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

 

foreach ($reports as $report)

{

$table->addRow();

$table->addCell(200, $styleCell)->addText($index, $fontStyle);

$stmt = $db->dbStream->prepare("SELECT * FROM `speakers` WHERE `id_report` =?");

$stmt->bindValue(1, $report['ID'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($stmt->rowCount()!= 0)

{

$userStrName = "";

$userStrGroup = "";

foreach ($users as $key => $user)

{

$stmt = $db->dbStream->prepare("SELECT * FROM `speakermeta` WHERE `speaker_id` =? ");

$stmt->bindValue(1, $user['ID'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$meta = $stmt->fetchAll(PDO::FETCH_ASSOC);

$tArr = array();

foreach ($meta as $m => $me)

{

$tArr[$me['meta_key']] = $me['meta_value'];

}

switch ($user['type']) {

case 'chuvsu':

$userStrGroup.= (strlen($tArr[$listUserTypes[$user['type']]]) > 0)? (isset($users[$key + 1]))? $tArr[$listUserTypes[$user['type']]].', ': $tArr[$listUserTypes[$user['type']]]: '';

$tArr['b_k'] = ($tArr['b_k'] == 1)? ($tArr['stip'] == 1)? "Бюджет, получает":"Бюджет": "Контракт";

break;

case '_chuvsu':

$userStrGroup.= (strlen($tArr[$listUserTypes[$user['type']]]) > 0)? (isset($users[$key + 1]))? $tArr[$listUserTypes[$user['type']]]." ".$tArr['inst'].', ': $tArr[$listUserTypes[$user['type']]]." ".$tArr['inst']: '';

//$table->addCell(2300, $styleCell)->addText($tArr['name_group'], $fontStyle);

//$table->addCell(2000, $styleCell)->addText("", $fontStyle);

break;

case 'school':

$userStrGroup.= (strlen($tArr[$listUserTypes[$user['type']]]) > 0)? (isset($users[$key + 1]))? $tArr['school'].', ': $tArr['school']: '';

//$table->addCell(2300, $styleCell)->addText($tArr['class'], $fontStyle);

//$table->addCell(2000, $styleCell)->addText("", $fontStyle);

break;

}

 

$userStrName.= (isset($users[$key + 1]))? $user['fio'].', ': $user['fio'];

}

$table->addCell(3000, $styleCell)->addText($userStrName, $fontStyle);

$table->addCell(1500, $styleCell)->addText($userStrGroup, $fontStyle);

}

else

{

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

}

$table->addCell(2000, $styleCell)->addText($report['name_report'], $fontStyle);

$stmt = $db->dbStream->prepare("SELECT * FROM `managers` INNER JOIN `positions` ON `positions`.`ID`=`managers`.`id_position` WHERE `id_report` =? ");

$stmt->bindValue(1, $report['ID'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$managers = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($stmt->rowCount()!= 0)

{

$str = "";

foreach ($managers as $m => $mng)

{

$str.= (isset($managers[$m + 1]))? $mng['fio']." ".mb_strtolower($mng['name']).', ': $mng['fio']." ".mb_strtolower($mng['name']).'';

}

$table->addCell(3000, $styleCell)->addText($str, $fontStyle);

}

else

{

$table->addCell(3000, $styleCell)->addText("", $fontStyle);

}

$index++;

}

$section->addTextBreak(1);

$section->addText('II. РЕШИЛИ:', null, 'textStyle');

$section->addText('1) По итогам обсуждения заслушанных докладов присудить следующие призовые места:', null, 'textStyle');

$PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);

// Add table

$table = $section->addTable('myOwnTableStyle');

$table->addRow();

$table->addCell(200, $styleCell)->addText('Место', $italicStyle);

$table->addCell(2000, $styleCell)->addText('Ф.И.О. докладчика', $italicStyle);

$table->addCell(3000, $styleCell)->addText('Группа', $italicStyle);

$table->addCell(1000, $styleCell)->addText('Бюджет/Контракт', $italicStyle);

$table->addCell(2000, $styleCell)->addText('Получает ли стипендию', $italicStyle);

$table->addCell(2000, $styleCell)->addText('№ телефона', $italicStyle);

foreach ($people as $user)

{

if ($user['place'] > 0)

{

$table->addRow();

$table->addCell(200, $styleCell)->addText($user['place'], $fontStyle);

$table->addCell(2000, $styleCell)->addText($user['fio'], $fontStyle);

$stmt = $db->dbStream->prepare("SELECT * FROM `speakermeta` WHERE `speaker_id` =? ");

$stmt->bindValue(1, $user['ID_SPEAKER'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$meta = $stmt->fetchAll(PDO::FETCH_ASSOC);

$tArr = array();

foreach ($meta as $m => $me)

{

$tArr[$me['meta_key']] = $me['meta_value'];

}

switch ($user['type']) {

case 'chuvsu':

$table->addCell(3000, $styleCell)->addText($tArr['name_group'], $fontStyle);

$table->addCell(1000, $styleCell)->addText(($tArr['b_k'] == 1)? "Бюджет":"Контракт", $fontStyle);

$table->addCell(2000, $styleCell)->addText(($tArr['stip'] == 1)? "да":"нет", $fontStyle);

$table->addCell(2000, $styleCell)->addText($tArr['phone'], $fontStyle);

break;

case '_chuvsu':

$table->addCell(3000, $styleCell)->addText($tArr['name_group'], $fontStyle);

$table->addCell(1000, $styleCell)->addText("", $fontStyle);

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

$table->addCell(2000, $styleCell)->addText($tArr['phone'], $fontStyle);

break;

case 'school':

$table->addCell(3000, $styleCell)->addText($tArr['class'], $fontStyle);

$table->addCell(1000, $styleCell)->addText("", $fontStyle);

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

break;

}

}

}

$section->addText('2) Рекомендовать к публикации в сборнике трудов конференции следующий доклад:', null, 'textStyle');

 

$table = $section->addTable('myOwnTableStyle');

$table->addRow();

$table->addCell(2500, $styleCell)->addText('Ф.И.О. докладчика', $italicStyle);

$table->addCell(2000, $styleCell)->addText('Группа', $italicStyle);

$table->addCell(3000, $styleCell)->addText('Название доклада', $italicStyle);

$table->addCell(2500, $styleCell)->addText('Ф.И.О. и должность научного руководителя', $italicStyle);

/*

*

*/

$stmt = $db->dbStream->prepare("SELECT * FROM `reports` WHERE `id_section` =? AND `is_recommend_STK` = 1");

$stmt->bindValue(1, $sectionID, PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

 

foreach ($reports as $report)

{

$table->addRow();

$stmt = $db->dbStream->prepare("SELECT * FROM `speakers` WHERE `id_report` =?");

$stmt->bindValue(1, $report['ID'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($stmt->rowCount()!= 0)

{

$userStrName = "";

$userStrGroup = "";

foreach ($users as $key => $user)

{

$stmt = $db->dbStream->prepare("SELECT * FROM `speakermeta` WHERE `speaker_id` =? ");

$stmt->bindValue(1, $user['ID'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$meta = $stmt->fetchAll(PDO::FETCH_ASSOC);

$tArr = array();

foreach ($meta as $m => $me)

{

$tArr[$me['meta_key']] = $me['meta_value'];

}

$userStrGroup.= (strlen($tArr[$listUserTypes[$user['type']]]) > 0)? (isset($users[$key + 1]))? $tArr[$listUserTypes[$user['type']]].', ': $tArr[$listUserTypes[$user['type']]]: '';

$userStrName.= (isset($users[$key + 1]))? $user['fio'].', ': $user['fio'];

}

$table->addCell(3000, $styleCell)->addText($userStrName, $fontStyle);

$table->addCell(1500, $styleCell)->addText($userStrGroup, $fontStyle);

}

else

{

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

$table->addCell(2000, $styleCell)->addText("", $fontStyle);

}

$table->addCell(2000, $styleCell)->addText($report['name_report'], $fontStyle);

$stmt = $db->dbStream->prepare("SELECT * FROM `managers` INNER JOIN `positions` ON `positions`.`ID`=`managers`.`id_position` WHERE `id_report` =? ");

$stmt->bindValue(1, $report['ID'], PDO::PARAM_INT);

try{$stmt->execute();}catch (PDOException $error) {trigger_error("Ошибка при работе с базой данных: {$error}");}

$managers = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($stmt->rowCount()!= 0)

{

$str = "";

foreach ($managers as $m => $mng)

{

$str.= (isset($managers[$m + 1]))? $mng['fio']." ".mb_strtolower($mng['name']).', ': $mng['fio']." ".mb_strtolower($mng['name']).'';

}

$table->addCell(3000, $styleCell)->addText($str, $fontStyle);

}

else

{

$table->addCell(3000, $styleCell)->addText("", $fontStyle);

}

}

 

$section->addTextBreak(1);

$styleTable1 = array('borderSize'=>1, 'borderColor'=>'FFFFFF', 'cellMargin'=>80);

$styleFirstRow1 = array('borderBottomSize'=>1, 'borderBottomColor'=>'FFFFFF', 'bgColor'=>'FFFFFF');

 

$PHPWord->addTableStyle('myOwnTab1', $styleTable1, $styleFirstRow1);

$table = $section->addTable('myOwnTab1');

 

for($i = 1; $i <= count($comisData); $i++) {

$table->addRow();

if($comisData[$i-1]['id_status'] == 1)

{

$table->addCell(6000)->addText('Председатель секции');

 

} elseif($comisData[$i-1]['id_status'] == 2)

{

$table->addCell(6000)->addText('Секретарь секции');

} else

{

$table->addCell(6000)->addText('Другие члены жюри');

}

$table->addCell(4000)->addText($comisData[$i-1]['fio']);

}

$table->addRow();

$table->addCell(6000)->addText('Научный руководитель СНО факультета');

// Save File

$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');

$uid = md5(uniqid(rand(), true));

$objWriter->save($uid.'.docx');

 

 

Интеграция с VKAPI

Для авторизации пользователей была использована интеграция с социальной сетью «В Контакте» при помощи VKAPI. Для этого на стороне бэкенда был написан класс для работы с методами. Работа введется при помощи JSON данных, которые декодируются в ассоциативный массив.

 

 


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: