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?
Related
I'm trying to convert an mysql-query to a query for Elasticsearch, but I think I am on the wrong way.
The mysql-query looks like the following:
WHERE foo = 0 OR (foo = 1 AND bar LIKE "%blub%")
The Elasticseach-query is created like the following:
$fieldFoo = 'attributes.core.foo.raw';
$fieldBar = 'attributes.core.bar.raw';
$firstQuery = new BoolQuery();
$firstQuery->add(new TermQuery($fieldBar, "0"), BoolQuery::SHOULD);
$secondQuery = new BoolQuery();
$secondQuery->add(new WildcardQuery($fieldFoo, "*" . $value . "|*"));
$secondQuery->add(new TermQuery($fieldBar, "1"));
$firstQuery->add($secondQuery, BoolQuery::MUST);
$search->addQuery($query);
But this one does not work. What can I try next?
The following solution works now:
$fieldFoo = 'attributes.core.foo.raw';
$fieldBar = 'attributes.core.bar.raw';
$query = new BoolQuery();
$firstQuery = new BoolQuery();
$firstQuery->add(new TermQuery($fieldBar, "0"), BoolQuery::SHOULD);`enter code here`
$secondQuery = new BoolQuery();
$secondQuery->add(new WildcardQuery($fieldFoo, "*" . $value . "|*"), BoolQuery::SHOULD);
$secondQuery->add(new TermQuery($fieldBar, "1"), BoolQuery::SHOULD);
$firstQuery->add($secondQuery, BoolQuery::SHOULD);
$query->add($firstQuery, BoolQuery::MUST);
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();
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
I have a html form (for blogposts) and I want to save everything in a database table. It works fine but when I add a column for an image, which can also be uploaded in the same html form, then it is not saving anything.
Here's the code:
$imagepath = 'https://myurl.com/uploads/' . $_FILES['image']['name'];
$db = new PDO($dsn, $dbuser, $dbpass);
$query = $db->prepare(
"INSERT INTO posts (author, title, text, date, image)
VALUES(:author, :title, :text, NOW()), '$imagepath'");
$query->execute(array("author" => $author, "title" => $title, "text" => $text));
$db = null;
Try This..
<?php
if(isset($_POST['Upload'])) // upload button press
{
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_temp = $_FILES['file']['tmp_name'];
$folder = "uploads/";
$file_url="http://localhost/../../uploads/$file_name"; //file location
move_uploaded_file($file_temp,"Song_uploads/".$file_name);
$sql="INSERT INTO imagepost(file_NAME,file_URL,file_SIZE) VALUES(:file_name,:file_url,:file_size)";
$stmt= $conn->prepare($sql);
$stmt->bindParam(':file_name',$file_name);
$stmt->bindParam(':file_url',$file_url);
$stmt->bindParam(':file_size',$file_size);
if($stmt->execute())
{
$message="<br/><h1> ---> "."[".$file_name."]"." File Has Been Uploaded !! </h1>";
}
else
{
$message="<br/> <h1> ---> "."[".$file_name."]"." File Not Be Uploaded !! Please Try Again !! </h1>";
}
}
?>
the closing parenthese is wrongly placed
"INSERT INTO posts (author, title, text, date, image)
VALUES(:author, :title, :text, NOW()), '$imagepath'");
should be
"INSERT INTO posts (author, title, text, date, image)
VALUES(:author, :title, :text, NOW(), '$imagepath' )");
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.