php spreadsheet- unable to view excel file - yii2

Hi I am working in yii2. I have a function in which I am making an excel file through my mysql query.
$sql = "SELECT SUM(OGP_Created) AS OGP_Created,SUM(UnVerifiedMSN) AS
Un_Verified_Meters,SUM(VerifiedMeters) AS Verified_Meters,SDCode AS
Sub_Div_Code
,SDName AS Sub_Div_Name FROM(
SELECT COUNT(DISTINCT od.`meter_id`) AS OGP_Created,0 AS UnVerifiedMSN,0 AS
VerifiedMeters, sd.`sub_div_code` AS 'SDCode', sd.`name` AS 'SDName'
FROM `ogp_detail` od
LEFT JOIN `survey_hesco_subdivision` sd ON od.`sub_div` = sd.`sub_div_code`
WHERE od.`meter_type` = '3-Phase'
GROUP BY sd.`name`
UNION ALL
SELECT 0 AS OGP_Created,COUNT(DISTINCT mp.`meter_id`) AS UnVerifiedMSN,0 AS
VerifiedMeters, sd.`sub_div_code` AS 'SDCode', sd.`name` AS 'SDName'
FROM `meter_ping` mp
INNER JOIN `meters` m ON mp.`meter_id` = m.`id`
INNER JOIN `survey_hesco_subdivision` sd ON mp.`sub_div_code` =
sd.`sub_div_code`
WHERE mp.`meter_type`= '3-Phase' AND mp.`meter_status` = 'Un Verified'
GROUP BY sd.`name`
UNION ALL
SELECT 0 AS OGP_Created,0 AS UnVerifiedMSN,COUNT(DISTINCT m.`id`) AS
VerifiedMeters, sd.`sub_div_code` AS 'SDCode', sd.`name` AS 'SDName'
FROM `meters` m
INNER JOIN `survey_hesco_subdivision` sd ON m.`sub_div` = sd.`sub_div_code`
WHERE m.`meter_type` = '3-Phase' AND m.`meter_status` = 'Installed'
GROUP BY sd.`name`
)z
GROUP BY SDName";
$result = Yii::$app->db->createCommand($sql)->queryAll();
Passing the $result
//create a xlsx file
$filename = $this->getAttachment($result);
getAttachment function
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'OGP Created')
->setCellValue('B1','Un Verified Meters')
->setCellValue('C1','Verified Meters')
->setCellValue('D1','Sub Div Code')
->setCellValue('E1','Sub Div Name');
foreach($results as $key => $result_data) {
$x = $key + 2;
$spreadsheet->setActiveSheetIndex(0)
->setCellValue("A$x", $result_data['OGP_Created'])
->setCellValue("B$x", $result_data['Un_Verified_Meters'])
->setCellValue("C$x", $result_data['Verified_Meters'])
->setCellValue("D$x", $result_data['Sub_Div_Code'])
->setCellValue("E$x", $result_data['Sub_Div_Name']);
}
$filename = 'Output.xlsx'; //save our workbook as this file name
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
die();
Now I when I run the above code. The file is downloaded but when I open the file it says
How can I make a correct excel file? Any help would be highly appreciated

Refer PhpSpreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'OGP Created')
->setCellValue('B1','Un Verified Meters')
->setCellValue('C1','Verified Meters')
->setCellValue('D1','Sub Div Code')
->setCellValue('E1','Sub Div Name');
foreach($results as $key => $result_data) {
$x = $key + 2;
$spreadsheet->setActiveSheetIndex(0)
->setCellValue("A$x", $result_data['OGP_Created'])
->setCellValue("B$x", $result_data['Un_Verified_Meters'])
->setCellValue("C$x", $result_data['Verified_Meters'])
->setCellValue("D$x", $result_data['Sub_Div_Code'])
->setCellValue("E$x", $result_data['Sub_Div_Name']);
}
$filename = 'Output.xlsx'; //save our workbook as this file name
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
die();

Related

Symfony3 : How to do a massive import from a CSV file as fast as possible?

I have a .csv file with more than 690 000 rows.
I found a solution to import data that works very well but it's a little bit slow... (around 100 records every 3 seconds = 63 hours !!).
How can I improve my code to make it faster ?
I do the import via a console command.
Also, I would like to import only prescribers that aren't already in database (to save time). To complicate things, no field is really unique (except for id).
Two prescribers can have the same lastname, firstname, live in the same city and have the same RPPS and professional codes. But, it's the combination of these 6 fields which makes them unique !
That's why I check on every field before create a new one.
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\ProgressBar;
use AppBundle\Entity\Prescriber;
class PrescribersImportCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
// the name of the command (the part after "bin/console")
->setName('import:prescribers')
->setDescription('Import prescribers from .csv file')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Show when the script is launched
$now = new \DateTime();
$output->writeln('<comment>Start : ' . $now->format('d-m-Y G:i:s') . ' ---</comment>');
// Import CSV on DB via Doctrine ORM
$this->import($input, $output);
// Show when the script is over
$now = new \DateTime();
$output->writeln('<comment>End : ' . $now->format('d-m-Y G:i:s') . ' ---</comment>');
}
protected function import(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getManager();
// Turning off doctrine default logs queries for saving memory
$em->getConnection()->getConfiguration()->setSQLLogger(null);
// Get php array of data from CSV
$data = $this->getData();
// Start progress
$size = count($data);
$progress = new ProgressBar($output, $size);
$progress->start();
// Processing on each row of data
$batchSize = 100; # frequency for persisting the data
$i = 1; # current index of records
foreach($data as $row) {
$p = $em->getRepository('AppBundle:Prescriber')->findOneBy(array(
'rpps' => $row['rpps'],
'lastname' => $row['nom'],
'firstname' => $row['prenom'],
'profCode' => $row['code_prof'],
'postalCode' => $row['code_postal'],
'city' => $row['ville'],
));
# If the prescriber doest not exist we create one
if(!is_object($p)){
$p = new Prescriber();
$p->setRpps($row['rpps']);
$p->setLastname($row['nom']);
$p->setFirstname($row['prenom']);
$p->setProfCode($row['code_prof']);
$p->setPostalCode($row['code_postal']);
$p->setCity($row['ville']);
$em->persist($p);
}
# flush each 100 prescribers persisted
if (($i % $batchSize) === 0) {
$em->flush();
$em->clear(); // Detaches all objects from Doctrine!
// Advancing for progress display on console
$progress->advance($batchSize);
$progress->display();
}
$i++;
}
// Flushing and clear data on queue
$em->flush();
$em->clear();
// Ending the progress bar process
$progress->finish();
}
protected function getData()
{
// Getting the CSV from filesystem
$fileName = 'web/docs/prescripteurs.csv';
// Using service for converting CSV to PHP Array
$converter = $this->getContainer()->get('app.csvtoarray_converter');
$data = $converter->convert($fileName);
return $data;
}
}
EDIT
According to #Jake N answer, here is the final code.
It's very very faster ! 10 minutes to import 653 727 / 693 230 rows (39 503 duplicate items!)
1) Add two columns in my table : created_at and updated_at
2) Add a single index of type UNIQUE on every column of my table (except id and dates) to prevent duplicate items with phpMyAdmin.
3) Add ON DUPLICATE KEY UPDATE in my query, to update just the updated_at column.
foreach($data as $row) {
$sql = "INSERT INTO prescripteurs (rpps, nom, prenom, code_prof, code_postal, ville)
VALUES(:rpps, :nom, :prenom, :codeprof, :cp, :ville)
ON DUPLICATE KEY UPDATE updated_at = NOW()";
$stmt = $em->getConnection()->prepare($sql);
$r = $stmt->execute(array(
'rpps' => $row['rpps'],
'nom' => $row['nom'],
'prenom' => $row['prenom'],
'codeprof' => $row['code_prof'],
'cp' => $row['code_postal'],
'ville' => $row['ville'],
));
if (!$r) {
$progress->clear();
$output->writeln('<comment>An error occured.</comment>');
$progress->display();
} elseif (($i % $batchSize) === 0) {
$progress->advance($batchSize);
$progress->display();
}
$i++;
}
// Ending the progress bar process
$progress->finish();
1. Don't use Doctrine
Try to not use Doctrine if you can, it eats memory and as you have found is slow. Try and use just raw SQL for the import with simple INSERT statements:
$sql = <<<SQL
INSERT INTO `category` (`label`, `code`, `is_hidden`) VALUES ('Hello', 'World', '1');
SQL;
$stmt = $this->getDoctrine()->getManager()->getConnection()->prepare($sql);
$stmt->execute();
Or you can prepare the statement with values:
$sql = <<<SQL
INSERT INTO `category` (`label`, `code`, `is_hidden`) VALUES (:label, :code, :hidden);
SQL;
$stmt = $this->getDoctrine()->getManager()->getConnection()->prepare($sql);
$stmt->execute(['label' => 'Hello', 'code' => 'World', 'hidden' => 1);
Untested code, but it should get you started as this is how I have done it before.
2. Index
Also, for your checks, have you got an index on all those fields? So that the lookup is as quick as possible.

Accessing dynamically created variables inside a powershell function

I've been working on this script that seemed simple enough in concept but is really boggling me with some things that just don't seem to work like I'd expect. The basic idea is the script is going to read a set of usernames and provide a user with a checkbox they can check for each account they want the system to create. With help from this site I was able to get a function that is able to dynamically create the variables and checkbox objects, but now I am having issues accessing their values. I just need to pull a boolean value for each name whether the box was checked or not. Here is the full code:
$form = New-Object System.Windows.Forms.Form
$flowlayoutpanel = New-Object System.Windows.Forms.FlowLayoutPanel
$buttonOK = New-Object System.Windows.Forms.Button
$usernames = "andrew", "beth", "charlie", "dave", "james", "george"
$totalvalues = ($usernames.count)
$formsize = 85 + (30 * $totalvalues)
$flowlayoutsize = 10 + (30 * $totalvalues)
$buttonplacement = 40 + (30 * $totalvalues)
$form_Load = {
foreach($user in $usernames){
$DynamicCheckBox = New-Variable -Name ("checkbox" + $user)
$DynamicCheckBox = New-object System.Windows.Forms.CheckBox
$DynamicCheckBox.Margin = '10, 8, 0, 0'
$DynamicCheckBox.Name = 'checkbox' + $_
$DynamicCheckBox.Size = '200, 22'
$DynamicCheckBox.Text = "" + $user
$DynamicCheckBox.TextAlign = 'MiddleLeft'
$flowlayoutpanel.Controls.Add($DynamicCheckBox)
}
}
$form.Controls.Add($flowlayoutpanel)
$form.Controls.Add($buttonOK)
$form.AcceptButton = $buttonOK
$form.AutoScaleDimensions = '8, 17'
$form.AutoScaleMode = 'Font'
$form.ClientSize = "500 , $formsize"
$form.FormBorderStyle = 'FixedDialog'
$form.Margin = '5, 5, 5, 5'
$form.MaximizeBox = $False
$form.MinimizeBox = $False
$form.Name = 'form1'
$form.StartPosition = 'CenterScreen'
$form.Text = 'Form'
$form.add_Load($form_Load)
$flowlayoutpanel.BorderStyle = 'FixedSingle'
$flowlayoutpanel.Location = '48, 13'
$flowlayoutpanel.Margin = '4, 4, 4, 4'
$flowlayoutpanel.Name = 'flowlayoutpanel1'
$flowlayoutpanel.Size = "400, $flowlayoutsize"
$flowlayoutpanel.TabIndex = 1
$buttonOK.Anchor = 'Bottom, Right'
$buttonOK.DialogResult = 'OK'
$buttonOK.Location = "383, $buttonplacement"
$buttonOK.Margin = '4, 4, 4, 4'
$buttonOK.Name = 'buttonOK'
$buttonOK.Size = '100, 30'
$buttonOK.TabIndex = 0
$buttonOK.Text = '&OK'
$form.ShowDialog()
foreach($user in $usernames){
$DynamicCheckBoxValue = Get-Variable -Name ('$checkbox' + $user) -Scope Script
write-host $DynamicCheckBoxValue
}
write-host $checkbox.Checked
I've tried playing with the scope settings for the variable being created in line 15, but if I change the scope to Script as I think it should be, I get a strange series of errors. Powershell tells me that the variable already exists (though this may be because they are still in my ISE session?). If I tell it to forcibly overwrite any that might be there that fixes that error, but either way I get errors that tell me that the variable does not exist, even when just right before powershell was complaining that the variables already did exist.
Get-Variable : Cannot find a variable with the name '$checkboxgeorge'.
At C:\Users\sheep\Untitled1.ps1:62 char:33
+ ... $DynamicCheckBoxValue = Get-Variable -Name ('$checkbox' + $user)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ($checkboxgeorge:String) [Get-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand
I'm not sure what is happening here and I'm fiddling with scopes as that seems like the culprit. If anyone here knows what the fix is could you also tell me why this is happening?
Even though i submitted this answer, I strongly recommend you to read this answer from TesselatingHeckler here that he kindly provided in the comments section to you.
Furthermore, although dynamic variables are a thing, in your case, that's a layer which proves to be useless and add complicated logic when this can be much more simple.
One better solution than dynamic variables for your scenario.
For instance, instead of creating a username array, use a hashtable which will still store your username but will have a "value" field which you can use to store your bolean and soon enough, when you have something more complex, you can store complete object inside the value field.
$usernames =
#{
'andrew'='';
'beth'='';
'charlie'='';
'dave'='';
'james'=''
'george'=''
}
Now that you have your hashtable, you can set your values using
#Settings some value - in your case, that would be done through the form
$usernames.andrew = 0
$usernames.dave = 1
You can even do it "dynamically"
$User = Read-Host # Asking which user here
$usernames.Item($User) = 1 # setting user "checkbox value" to 1 here
For instance, in that last example, the username is stored into $User and the value of that user is then set to '1' .
It gives you everything you wanted without the overhead of setting dynamic variables.
A simple statement to display who checked their checkbox.
Since everything is in the $Usernames hashtable, it is easy to manipulate, store into a csv file, etc... without any additional work.
# Display users checked status their checkboxes
$usernames | ft Name, #{n='IsChecked';e={$_.Value -eq 1}}
Below line is not making any change to variable $DynamicCheckBox.
$DynamicCheckBox = New-Variable -Name ("checkbox" + $user)
I have modified the script to find out which users were checked. Hope this will help.
Code:-
$form = New-Object System.Windows.Forms.Form
$flowlayoutpanel = New-Object System.Windows.Forms.FlowLayoutPanel
$buttonOK = New-Object System.Windows.Forms.Button
$usernames = "andrew", "beth", "charlie", "dave", "james", "george"
$totalvalues = ($usernames.count)
$formsize = 85 + (30 * $totalvalues)
$flowlayoutsize = 10 + (30 * $totalvalues)
$buttonplacement = 40 + (30 * $totalvalues)
$script:CheckBoxArray = #()
$form_Load = {
foreach($user in $usernames){
$DynamicCheckBox = New-object System.Windows.Forms.CheckBox
$DynamicCheckBox.Margin = '10, 8, 0, 0'
$DynamicCheckBox.Name = $user
$DynamicCheckBox.Size = '200, 22'
$DynamicCheckBox.Text = "" + $user
$DynamicCheckBox.TextAlign = 'MiddleLeft'
$flowlayoutpanel.Controls.Add($DynamicCheckBox)
$script:CheckBoxArray += $DynamicCheckBox
}
}
$form.Controls.Add($flowlayoutpanel)
$form.Controls.Add($buttonOK)
$form.AcceptButton = $buttonOK
$form.AutoScaleDimensions = '8, 17'
$form.AutoScaleMode = 'Font'
$form.ClientSize = "500 , $formsize"
$form.FormBorderStyle = 'FixedDialog'
$form.Margin = '5, 5, 5, 5'
$form.MaximizeBox = $False
$form.MinimizeBox = $False
$form.Name = 'form1'
$form.StartPosition = 'CenterScreen'
$form.Text = 'Form'
$form.add_Load($($form_Load))
$flowlayoutpanel.BorderStyle = 'FixedSingle'
$flowlayoutpanel.Location = '48, 13'
$flowlayoutpanel.Margin = '4, 4, 4, 4'
$flowlayoutpanel.Name = 'flowlayoutpanel1'
$flowlayoutpanel.AccessibleName = 'flowlayoutpanel1'
$flowlayoutpanel.Size = "400, $flowlayoutsize"
$flowlayoutpanel.TabIndex = 1
$buttonOK.Anchor = 'Bottom, Right'
$buttonOK.DialogResult = 'OK'
$buttonOK.Location = "383, $buttonplacement"
$buttonOK.Margin = '4, 4, 4, 4'
$buttonOK.Name = 'buttonOK'
$buttonOK.Size = '100, 30'
$buttonOK.TabIndex = 0
$buttonOK.Text = '&OK'
$form.ShowDialog()
foreach($cbox in $CheckBoxArray){
$cbox.Name + " is " + $cbox.CheckState
}
Remove-Variable checkbox*
Input:-
Output:-
This might push you in the right direction.
When you use Get-Variable you have to exclude the $. So use:
Get-Variable -Name ("checkbox" + $user) -Scope Script

trouble setting up wiki family

I've installed MediaWiki 1.27.1 and managed to get a basic single-wiki setup working. Now I'm trying to change it into a wiki family according to the instructions at Manual:Wiki_family. Here's what I'm aiming for:
wiki.mysite.com/ #public wiki
wiki.mysite.com/priv1 #private wiki 1
wiki.mysite.com/priv2 #private wiki 2
The result I got:
wiki.mysite.com shows the public wiki, as expected.
wiki.mysite.com/priv1 returns 404
wiki.mysite.com/priv2 returns 404
[edit: added message text] The text of the 404 message:
Not Found
The requested document was not found on this server.
Web Server at mysite.com
What I did:
I followed the steps outlined in the manual, generated the 3 copies of LocalSettings.php, and renamed them. I then modified the main LocalSettings.php to the following:
<?php
if ( !defined( 'MEDIAWIKI' ) ) {
exit;
}
## Database settings - cut-and-pasted out from the 3 sub-wikis' LocalSettings.php
$wgDBtype = "mysql";
$wgDBserver = "localhost";
$wgDBname = "db_wiki";
$wgDBuser = "db_wiki_user";
$wgDBpassword = "password";
$callingurl = strtolower( $_SERVER['REQUEST_URI'] ); // get the calling url
if ( strpos( $callingurl, '/priv1' ) === 0 ) {
require_once 'LocalSettings_priv1.php';
} elseif ( strpos( $callingurl, '/priv2' ) === 0 ) {
require_once 'LocalSettings_priv2.php';
} elseif ( strpos( $callingurl, '/' ) === 0 ) {
require_once 'LocalSettings_public.php';
} else {
header( 'HTTP/1.1 404 Not Found' );
echo "This wiki (\"" . htmlspecialchars( $callingurl ) . "\") is not available. Check configuration.";
exit( 0 );
}
For test, I've tried changing the file name in the require_once 'localsettings_public.php' line to each sub-wiki's LocalSettings.php file; when I open wiki.mysite.com, the related sub-wiki does get shown correctly. The URLs with the subdirectory path continue to return 404, however.
Any idea what's wrong with my setup?

Import XML File into mySQL with PDO

I need to import an XML file into an MySQL database.
I got an code already - but it's a few years old and don't use PDO and I did'nt get it working now on an new server with PHP7 and MySQL 5.5.
Would be very nice, if someone could help me with an working solution.
My XML file:
<amateures>
<amateur>
<id>
<login>
<figur>
<vote_rating>
<haarfarbe>
<gewicht>
<groesse>
<plz>
<sternzeichen>
<vorlieben>
<vorlieben_en>
<uebermich>
<uebermich_en>
<geschlecht>
<staat>
<gebtag>
<regdate>
<urls>
<profil>
<register>
</urls>
<images>
<overview>
<overview_fsk16>
<overview_big>
<overview_fsk16_big>
</images>
<videos>
<video>
<title>
<title_en>
<beschreibung>
<beschreibung_en>
<playtime>
<id>
<img_fsk16>
<img>
<imgani>
<videourl>
<category>
<category>
<category>
</video>
</videos>
</amateur>
<amateur>
[...]
</amateur>
</amateures>
I need the data in 3 tables:
Following data I need for table "amateure":
<amateur>
<id>
<login>
<figur>
<vote_rating>
<haarfarbe>
<gewicht>
<groesse>
<plz>
<sternzeichen>
<vorlieben>
<vorlieben_en>
<uebermich>
<uebermich_en>
<geschlecht>
<staat>
<gebtag>
<regdate>
<urls>
<profil>
<register>
</urls>
<images>
<overview>
<overview_fsk16>
<overview_big>
<overview_fsk16_big>
</images>
</amateur>
table "amateur_vid" should contain:
<videos>
<video>
<title>
<title_en>
<beschreibung>
<beschreibung_en>
<playtime>
<id>
<img_fsk16>
<img>
<imgani>
<videourl>
</video>
</videos>
and the table "amateur_cat" should contain:
<category>
The field "id" from section must be add to table "amateur_vid" and the filed "id" from section must be add to the table "amateur_cat".
This is my code - in this case only one category will be imported. I don't know how to do a loop over the nodes:
#!/usr/bin/php -n
<?php
function OpenDB () {
$connect = mysqli_connect('localhost','#','#');
if(!$connect)
die ("Connection to SQL-Server failed!");
$database = mysqli_select_db($connect, "DATABASE");
if(!$database)
die ("Selection of Database failed!");
return $connect;
}
$connect = OpenDB();
$count = 0;
$countnew = 0;
$countvid = 0;
$starttime = time();
$xml = simplexml_load_file("FILE.xml");
$query = "update amateur set deleted = 1";
mysqli_query($connect, $query);
$query = "delete from amateur_vid";
$res = mysqli_query($connect, $query);
foreach ($xml->amateur as $amateur) {
$count++;
$amateur_id = $amateur->id;
$amateur_login = utf8_decode($amateur->login);
$amateur_figur = $amateur->figur;
$amateur_vote_rating = $amateur->vote_rating;
$amateur_haarfarbe = $amateur->haarfarbe;
$amateur_gewicht = $amateur->gewicht;
$amateur_groesse = $amateur->groesse;
$amateur_plz = $amateur->plz;
$amateur_sternzeichen = $amateur->sternzeichen;
$amateur_vorlieben = $amateur->vorlieben;
$amateur_vorlieben_en = $amateur->vorlieben_en;
$amateur_uebermich = $amateur->uebermich;
$amateur_uebermich_en = $amateur->uebermich_en;
$amateur_geschlecht = $amateur->geschlecht;
$amateur_staat = $amateur->staat;
$amateur_gebtag = $amateur->gebtag;
$amateur_regdate = $amateur->regdate;
foreach ($amateur->urls as $url) {
$amateur_profil = $url->profil;
$amateur_register = $url->register;
}
foreach ($amateur->images as $image) {
$amateur_overview = $image->overview;
$amateur_overview_fsk16 = $image->overview_fsk16;
$amateur_overview_big = $image->overview_big;
$amateur_overview_fsk16_big = $image->overview_fsk16_big;
}
$amateur_vorlieben = mysqli_escape_string($connect, $amateur_vorlieben);
$amateur_vorlieben_en = mysqli_escape_string($connect, $amateur_vorlieben_en);
$amateur_uebermich = mysqli_escape_string($connect, $amateur_uebermich);
$amateur_uebermich_en = mysqli_escape_string($connect, $amateur_uebermich_en);
$query = "select * from amateur where amateur_id = $amateur_id";
$res = mysqli_query($connect, $query);
if(mysqli_num_rows($res) == 0) {
$countnew++;
$query = "insert into amateur (amateur_id, amateur_login, amateur_figur, amateur_vote_rating, amateur_haarfarbe, amateur_gewicht, amateur_groesse, amateur_plz, amateur_sternzeichen, amateur_vorlieben, amateur_vorlieben_en, amateur_uebermich, amateur_uebermich_en, amateur_geschlecht, amateur_staat, amateur_gebtag, amateur_regdate, amateur_profil, amateur_register, amateur_overview, amateur_overview_fsk16, amateur_overview_big, amateur_overview_fsk16_big) values ($amateur_id, '$amateur_login', '$amateur_figur', '$amateur_vote_rating', '$amateur_haarfarbe', '$amateur_gewicht', '$amateur_groesse', '$amateur_plz', '$amateur_sternzeichen', '$amateur_vorlieben', '$amateur_vorlieben_en', '$amateur_uebermich', '$amateur_uebermich_en', '$amateur_geschlecht', '$amateur_staat', '$amateur_gebtag', '$amateur_regdate', '$amateur_profil', '$amateur_register', '$amateur_overview', '$amateur_overview_fsk16', '$amateur_overview_big', '$amateur_overview_fsk16_big')";
$res = mysqli_query($connect, $query);
} else {
$query = "update amateur set amateur_login='$amateur_login', amateur_figur='$amateur_figur', amateur_vote_rating='$amateur_vote_rating', amateur_haarfarbe='$amateur_haarfarbe', amateur_gewicht='$amateur_gewicht', amateur_groesse='$amateur_groesse', amateur_plz='$amateur_plz', amateur_sternzeichen='$amateur_sternzeichen', amateur_vorlieben='$amateur_vorlieben', amateur_vorlieben_en='$amateur_vorlieben_en', amateur_uebermich='$amateur_uebermich', amateur_uebermich_en='$amateur_uebermich_en', amateur_geschlecht='$amateur_geschlecht', amateur_staat='$amateur_staat', amateur_gebtag='$amateur_gebtag', amateur_regdate='$amateur_regdate', amateur_profil='$amateur_profil', amateur_register='$amateur_register', amateur_overview='$amateur_overview', amateur_overview_fsk16='$amateur_overview_fsk16', amateur_overview_big='$amateur_overview_big', amateur_overview_fsk16_big='$amateur_overview_fsk16_big', deleted=0 where amateur_id = $amateur_id";
$res = mysqli_query($connect, $query);
if(!$res)
die($query);
}
foreach ($amateur->videos as $videos) {
foreach ($videos->video as $video) {
$vids_title = $video->title;
$vids_title_en = $video->title_en;
$vids_beschreibung = $video->beschreibung;
$vids_beschreibung_en = $video->beschreibung_en;
$vids_playtime = $video->playtime;
$vids_id = $video->id;
$vids_img_fsk16 = $video->img_fsk16;
$vids_img = $video->img;
$vids_imgani = $video->imgani;
$vids_videourl = $video->videourl;
$vids_category = $video->category;
$query = "insert into amateur_vid (amateur_id, vids_title, vids_title_en, vids_beschreibung, vids_beschreibung_en, vids_playtime, vids_id, vids_img_fsk16, vids_img, vids_imgani, vids_videourl, vids_category) values ($amateur_id, '$vids_title', '$vids_title_en', '$vids_beschreibung', '$vids_beschreibung_en', '$vids_playtime', '$vids_id', '$vids_img_fsk16', '$vids_img', '$vids_imgani', '$vids_videourl', '$vids_category')";
$res = mysqli_query($connect, $query);
$setid = mysqli_insert_id($connect);
$countvid++;
}
}
}
$query = "delete from amateur where deleted = 1";
mysqli_query($connect, $query);
?>
I would be really happy, if someone could help me with an working code snippet for my problem.
Thanks in advance.
Bee
I could change my old script and it's working now.
The only thing I did not get working is the <categories> section.
I need the categories in an seperate table - or, add the categories comma separated into one field.
Someone has an solution for this?

MatLab Save image to database using database toolbox

Is it possible to insert or save an image to a database table using MatLab?
Here's my code:
%Code for Database Login
conn = database('vlmsystem','admin','vlog');
indata = imread('C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\images database\auto1.jpg');
a = getframe(h);
indata = a.cdata;
hgsave(h, 'tempfile.fig')
fid = fopen('tempfile.fig', 'r')
indata = fread(fid, inf, '*uint8')
fclose(fid)
s = size(indata);
bdata = reshape(indata,[],1);
x = conn.Handle
StatementObject = x.preparestatement(insertcommand);
StatementObject.setObject(1,bdata)
StatementObject.execute
close(StatementObject)
dbpath = 'C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\vlogdbase.mdb';
tableName = 'vehicleLog';
colnames = {'date_time','plate_number','login_logout','physical_feature'}
colnames1 = {'date_time'}
colnames2 = {'plate_number'}
colnames3 = {'login_logout'}
colnames4 = {'physical_feature'}
dat = datestr(now);
pltno = (f);
lilo = 'login';
physf = {bdata}
coldata = {dat,pltno,lilo,}
insert(conn,tableName,colnames,coldata);
close(conn);
And I am getting this error.
Error using graphicsversion Input was not a valid graphics object
Error in getframe (line 50) usingMATLABClasses =
~graphicsversion(parentFig, 'handlegraphics');
Error in licenseplate>StartKnop_Callback (line 248) a = getframe(h);
Tried copying this solution but I can't seem to make it work. Here's the link.
EDIT: Fix Code....but... how to insert binary data into the database.
There's no binary option in the database. The result won't feed into the table.
%Code for Database Login
conn = database('vlmsystem','admin','vlog');
indata = imread('C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\images database\auto1.jpg');
s = size(indata);
bdata = reshape(indata,[],1);
dbpath = 'C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\vlogdbase.mdb';
tableName = 'vehicleLog';
colnames = {'date_time','plate_number','login_logout','physical_feature'}
colnames1 = {'date_time'}
colnames2 = {'plate_number'}
colnames3 = {'login_logout'}
colnames4 = {'physical_feature'}
dat = datestr(now);
pltno = (f);
lilo = 'login';
physf = {bdata}
coldata = {dat,pltno,lilo,physf}
insert(conn,tableName,colnames,coldata);
close(conn);
Please read what you are copying.
The solution says:
Alternatively, if you have a figure and want to save a snapshot of it, use the command below:
You copied both blocks, one that reads files, one hat uses getframe to read a frame from a handle.