Insert image binary from xml data to mysql in PHP - php

I have some photos (not big, only 8kb) in mysql database (in my desktop). the field type is blob. i want to export the table to xml file then upload it to my database website. but it not success. Here is what i have done :
Exporting the data to xml (in my computer desktop):
FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.Write,FileShare.None);
StreamWriter sw = new StreamWriter(fs,Encoding.ASCII);
ds.WriteXml(sw); //write the xml from the dataset ds
Then upload the xml from my joomla website. i load the xml before insert it to the database
...
$obj = simplexml_load($filename);
$cnt = count($obj->mydata); //mydata is the table name in the xml tag
for($i=0;$i<cnt;$i++)
{
...
$myphoto = 'NULL';
if(!empty($obj->mydata[$i]->myphoto))
{
$myphoto = base64_code($obj->mydata[$i]->myphoto);
}
//insert to the database
$sqlinsert = "insert into jos_myphoto (id,myphoto) values(".$i.",".$myphoto.")";
...
}
...
it keep telling me 'DB function failed'. when value of $myphoto is null, the query work well but if $myphoto is not null, the error appears. i think there is something wrong with the code
$myphoto = base64_code($obj->mydata[$i]->myphoto).
i try to remove base64_code function but it dont work. How to solve this problem? Sorry for my bad english

Your data may contain which needs escaping put mysql_real_escape_string() function and try
It is always a good habit to store data using this function which save you from sql injection also.
And put quotes around the column data.
$sqlinsert = "insert into jos_myphoto (id,myphoto)
values(".$i.",'".mysql_real_eascape_string($myphoto)."')";

Related

What happens to binary files in file_get_contents?

I'm trying to read a file in php and store it as a varbinary in sql server. The process works for text files, but I'm still having trouble with images.
I'm using the following lines to read the file contents into a string, but I'm not sure that that's not where my problem lies:
$data = NULL;
$validators = NULL;
if($file = file_save_upload('file', $validators, FALSE, 0)){
$data = file_get_contents($file->getFileUri());
$filename = $file->getFilename();
}
Then I pass the $data string to a prepared statement:
$conn = $this->_get_connection();
$sql = "
EXEC JC_Update_Document_SP
...
?,
...;
";
$file_input = [
[$data, NULL, NULL, SQLSRV_SQLTYPE_VARBINARY],
];
$stmt = sqlsrv_prepare($conn, $sql, $file_input);
if(sqlsrv_execute($stmt) === false){
die(print_r(sqlsrv_errors(), true));
}
where the $data field feeds into a varbinary column in a stored procedure in the database.
Another method I tried involved converting the $data varchar to a varbinary(max) field in the database, but either way, I get back a broken image.
So my question is this... is file_get_contents messing up my binary data? How would I read the image file and upload it to the database for later retrieval?
I found the bin2hex function. I'm still unclear on why this is needed, but it gets the job done.

Laravel Raw Bulk insert

I wrote a function in a Controller used in the Laravel Framework. The function gets the file path of an *.csv file and then inserts all elements of this *.csv file with a raw bulk insert statement into the database. The problem is that the elements are not put in the database table when the function is executed. I do not get any errors, too. When I execute the Query in SQL Server Manager it inserts the elements without problems. What am I doing wrong and is there a better way to bulk insert the elements of an csv file to the database?
Here is the code for the function:
public static function bulkInsertCSV($filePath){
$sql = "use [testDatabase] BULK INSERT [dbo].[testTable]
FROM '" . $filePath . "' WITH (FIELDTERMINATOR = ';',"
. "ROWTERMINATOR = '\\n' );";
//DB::statement($sql);
DB::statement(DB::raw($sql));
}
Best regards,
Yalcin
I like using the laravel-excel library for dealing with my CSV files, it makes it a bit easier to manage and feels more "laravel-y" to me.
The laravel/excel lbirary: http://www.maatwebsite.nl/laravel-excel/docs/getting-started#installation library.
What you'd then do is somewhat simple:
Excel::filter('chunk')->load($filePath)->chunk(500, function($rows){
foreach($rows as $row) {
$data = collect([]);
foreach(App\TestTable::getFillable() as $fillable ) {
if (isset($row[$fillable])) {
$data->put($fillable, $row[$fillable]);
}
}
App\TestTable::create($data->toArray());
}
});
Notes:
Using chunk ensures we don't run out of memory.
The getFillable() methods assumes you defined the protected $fillable = []; properties on your TestTable model.
The column names from your testTable match the column names from your csvfile.
Hopefully this helps you.

Getting unwanted or unknow data at the end of each data in mysql

I have a text file ,I need to get data from text file and insert into MySQL my code is:
$data = file_get_contents("words.txt");
$convert = explode("\n", $data);
$con = mysql_connect("localhost","root","pwd") or die('couldnot connect to database'.mysql_error());
for ($i=0;$i<count($convert);$i++)
{
mysql_select_db("DB",$con);
$sql = "INSERT INTO Table VALUES ('".$convert[0]."')";
}
This code inserted data perfectly into database. But an unusual string is inserting at the end of each word. How can I remove that. Thanks in advance. My output looks like.
After each word a string which looks like zero is adding when I get this data to a form text box this unusual string is acting as enterby which cursor is going to next line in textbox
This char could be "\r", try:
$sql = "INSERT INTO Table VALUES ('".trim($convert[0])."')";

How to retrieve data from MySQL database and save it to xml file

Need your help as Im badly stuck here. I have MySQL database and HTML form.I can connect to my database through that form without any problem. All my buttons (FIND, DELETE, UPDATE and ADD) also work perfectly.Now I decided to add PRINT button which suppose to export retrieved data to an xml file(that will be converted to pdf file later but I know how to deal with that). Any idea how or where to start??? Is there some php function I can use?
I actually resolved that issue by creating function for my PRINT button and then calling that function later. All working perfectly.
function printRecords($query){
global $ID, $Name, $Address,$Country, $Ph_number;
$result = mysql_query($query);
$resultCount = mysql_num_rows($result);
$query= 'SELECT ID, Name, Address , Country, Ph_number FROM people';
$fp= #fopen ("somefile.xml","w")or
die ("Could not open file");
$data = "";
for ($r=0; $r<$resultCount; $r++) {
$rec = mysql_fetch_assoc($result);
$data = sprintf("<Name>%s</Name>\r\n<Address>%s</Address>\r\n
<Ph_number>%s</Ph_number>\r\n"
$rec['Name'], $rec['Address'], $rec['Ph_number'] );
fwrite($fp, $data);
}
#fclose($fp);
return($resultCount);
}
Tried xml export via mysql command line ?
e.g.
mysql -uroot -p --xml -e 'SELECT * FROM mydb.Table1' > table1.xml
See the MySQL manual command options for xml
And I just saw that you have access to the database thru an html form, and maybe can't run a command line?
Otherwise you could do your own xmldoc from a select, a simple query I made here SQLFIDDLE.
create table animal(id int, name char(10));
insert into animal values
(1,'dog'),
(2,'cat'),
(3,'mouse'),
(4,'horse'),
(5,'cow');
SELECT
CONCAT('\n<animals>\n',
GROUP_CONCAT('<animal id=', id, '>',name,'</animal>\n' SEPARATOR ''),
'</animals>') AS xmldoc
FROM animal;
Output would be:
<animals>
<animal id=1>dog</animal>
<animal id=2>cat</animal>
<animal id=3>mouse</animal>
<animal id=4>horse</animal>
<animal id=5>cow</animal>
</animals>
The sqlfiddle
You can connect to your database via php application and then with a custom functionality yu can export data like xml, cvs, excel or html whatever you need.
To export xml format via php check this link. it works
How can I export to an XML file instead of printing it on screen?

Transform MySQL table and rows

I have one problem here, and I don't even have clue what to Google and how to solve this.
I am making PHP application to export and import data from one MySQL table into another. And I have problem with these tables.
In source table it looks like this:
And my destination table has ID, and pr0, pr1, pr2 as rows. So it looks like this:
Now the problem is the following: If I just copy ( insert every value of 1st table as new row in second) It will have like 20.000 rows, instead of 1000 for example.
Even if I copy every record as new row in second database, is there any way I can fuse rows ? Basically I need to check if value exists in last row with that ID_, if it exist in that row and column (pr2 for example) then insert new row with it, but if last row with same ID_ does not have value in pr2 column, just update that row with value in pr2 column.
I need idea how to do it in PHP or MySQL.
So you got a few Problems:
1) copy the table from SQL to PHP, pay attention to memory usage, run your script with the PHP command Memory_usage(). it will show you that importing SQL Data can be expensive. Look this up. another thing is that PHP DOESNT realese memory on setting new values to array. it will be usefull later on.
2)i didnt understand if the values are unique at the source or should be unique at the destination table.. So i will assume that all the source need to be on the destination as is.
I will also assume that pr = pr0 and quant=pr1.
3) you have missmatch names.. that can also be an issue. would take care of that..also.
4) will use My_sql, as the SQL connector..and $db is connected..
SCRIPT:
<?PHP
$select_sql = "SELECT * FROM Table_source";
$data_source = array();
while($array_data= mysql_fetch_array($select_sql)) {
$data_source[] = $array_data;
$insert_data=array();
}
$bulk =2000;
foreach($data_source as $data){
if(isset($start_query) == false)
{
$start_query = 'REPLACE INTO DEST_TABLE ('ID_','pr0','pr1','pr2')';
}
$insert_data[]=implode(',',$data).',0)';// will set 0 to the
if(count($insert_data) >=$bulk){
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = array();
} //CHECK THE SYNTAX IM NOT SURE OF ALL OF IT MOSTLY THE SQL PART>> SEE THAT THE QUERY IS OK
}
if(count($insert_data) >=$bulk) // IF THERE ARE ANY EXTRA PIECES..
{
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = null;
}
?>
ITs off the top off my head but check this idea and tell me if this work, the bugs night be in small things i forgot with the QUERY structure, print this and PASTE to PHPmyADMIN or you DB query and see its all good, but this concept will sqve a lot of problems..

Categories