How to insert html code in mysql database? - php

I have copies text from many html files into one text file/variable and I wants to insert this data(basically html code) into mysql database. I have tried mysql_real_escape_string. But it is still no working. This is what I am doing :
$contentFromHtmlFile=file_get_contents($file);
$all_html_content.=$contentFromHtmlFile;
$all_html_content=mysql_real_escape_string($all_html_content);
$insert_query = "insert into $databasetable (pdf_id,pdf_text_data) values (190,$all_html_content);";
mysql_query($insert_query) or die(mysql_error());
This is the error :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<meta charset=\"utf-8\" />\n\n<div id=\"jpedal\" style=\&quo' at line 1
Here link of text I wants to insert: http://pastebin.com/F3BD745h

You have put string values inside single quotes:
$insert_query = "insert into $databasetable(pdf_id,pdf_text_data)values(190,'$all_html_content');";
P.S:mysql_ function are depricared , don't use them. Use mysqli or PDO.

Wrap your variable around single quotes to signify that it's a string (in this case):
$insert_query = "INSERT INTO $databasetable(pdf_id, pdf_text_data)
VALUES(190, '$all_html_content');";
^ ^
Also, if you do not need to use the string for searching or any similar operations, I'd recommend converting it an ordinary string with base64_encode():
$contentFromHtmlFile = file_get_contents($file);
$all_html_content .= $contentFromHtmlFile;
$all_html_content = base64_encode($all_html_content);
$all_html_content = mysql_real_escape_string($all_html_content);

Related

Apostrophe causing problems with insert

Hi I am using php to insert some data into a MS Access Database, which works fine in most cases, the only time it doesnt work, as far as I can see is where there is an ' in the field, in this case its an address i.e. St John's Road.
This is the query statement I am using:
$sql = "insert into tempaddress (`id`, `StreetAddress`, `Place`, `PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."','$SearchTerm')"; CustomQuery($sql);
And this is the error I am getting http://prntscr.com/58jncv
I'm fairly sure it can only be the ' within the string text that is messing it up, how can i change?
Apostrophes breaks SQL strings. So you should add slashes before each apostrophe in your SQL strings manually or use PHP's built in function addslashes().
Example:
$sql = "INSERT INTO myTable (value) VALUES ('Text that shouldn't break')";
$sql = addslashes($sql); // outputs "INSERT INTO myTable (value) VALUES ('Text that shouldn\\'t break')"
Source : php.net/manual/en/function.addslashes.php
Thanks, in the end I went with str_replace("'", "", $string);
You are using ' ' quote with the php variable $SearchTerm and use a backslash before column name.
Change your query statement to this:
$sql = "insert into tempaddress (\`id\`, \`StreetAddress\`, \`Place\`, \`PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."',$SearchTerm)"; CustomQuery($sql);

php insert data from fetch array to other table on version 5.4

I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.

Insert, Update, Create Table, queries not working in wampserver

I've been using wampserver for a php project, but DML queries are not working for me. Here is some test code I've been using
$query='insert into register(first_name) values("swagmaster")';
echo($query);
$query = mysqli_real_escape_string($connection,$query);
echo"<br>$query";
if(mysqli_real_query($connection,"'".$query."'")===TRUE)
{
echo"woohoo!";
}
else
{
echo"query failed";
}
echo(mysqli_error($connection));
I get the following output when i run this:
insert into register(first_name) values("swagmaster")
insert into register(first_name) values(\"swagmaster\") query failed
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''insert into register(first_name) values(\"swagmaster\")'' at line 1
However, a select statement works fine. I suspect the issue is in mysql settings. Any suggestions?
UPDATE:
Using a combination of your tips, the query is now working. Thank you all!
Please try this query
$query = "INSERT INTO `register` SET `fieldname`='{$vaue}',`field2`='{$value2}'";
Change the query from
$query='insert into register(first_name) values("swagmaster")';
to
$query="insert into register(first_name) values('swagmaster')";
Also as Fred-ii said you dont need to add ' here
if(mysqli_real_query($connection,"'".$query."'")===TRUE)
change to
if(mysqli_real_query($connection,$query)===TRUE)
You used
$query = mysqli_real_escape_string($connection,$query);
But this escaped all quotes in query. This is incorrect. For protected fro SQL injection you should use escape function only to value instead query.
For your example you not need this string.
But if you use variables then you should use it
$value = "swagmaster";
$value = mysqli_real_escape_string($value);
$query='insert into register(first_name) values("' . $value . '")';
In $query is already correct query. And add quotes is incorrect. Just use
if(mysqli_real_query($connection, $query)===TRUE)

Insert a record with an apostrophe mysql php

I want to insert a record with an apostrophe into a MySQL database using PHP. Following is my code:
$importer_name =mysql_escape_string ($objWorksheet->getCellByColumnAndRow(1,3)->getValue());
$exporter_name = $objWorksheet->getCellByColumnAndRow(1, 3)->getValue();
$prod_quantity_unit = $objWorksheet->getCellByColumnAndRow(1,6)->getValue();
$prod_fob_value = $objWorksheet->getCellByColumnAndRow(5,6)->getValue();
$prod_quantity = $objWorksheet->getCellByColumnAndRow(1,8)->getValue();
$prod_fob_unit= $objWorksheet->getCellByColumnAndRow(5,8)->getValue();
$prod_gross_waight= $objWorksheet->getCellByColumnAndRow(1,10)->getValue();
$prod_cif_value= $objWorksheet->getCellByColumnAndRow(5,10)->getValue();
$prod_net_weight= $objWorksheet->getCellByColumnAndRow(1,12)->getValue();
$prod_cif_unit_price= $objWorksheet->getCellByColumnAndRow(5,12)->getValue();
$prod_brand= $objWorksheet->getCellByColumnAndRow(5,14)->getValue();
$hs_code = $objWorksheet->getCellByColumnAndRow(1,17)->getValue();
$shipping_date = $objWorksheet->getCellByColumnAndRow(5,17)->getValue();
$customs = $objWorksheet->getCellByColumnAndRow(1,19)->getValue();
$transport_company = $objWorksheet->getCellByColumnAndRow(5,19)->getValue();
$country_of_origin = $objWorksheet->getCellByColumnAndRow(1,21)->getValue();
$transport_mode = $objWorksheet->getCellByColumnAndRow(5,21)->getValue();
$country_of_trade = $objWorksheet->getCellByColumnAndRow(1,23)->getValue();
$hs_code_description = $objWorksheet->getCellByColumnAndRow(1,26)->getValue();
$product_description = $objWorksheet->getCellByColumnAndRow(1,28)->getValue();
$insertquery="INSERT INTO tb_peru_data
(importer_name,exporter_name,product_quantity_unit,
product_fob_unit,product_quantity,product_fob_value,
product_gross_weight,product_cif_value,
product_net_weight,product_cif_unit_price,
product_brand,shipping_hs_code,shipping_date,
shipping_customs,shipping_transport_company,
shipping_country_of_origin,shipping_transport_mode,
shipping_country_of_trade,hs_code_description,
product_description)
VALUES
('$importer_name','$exporter_name','$prod_quantity_unit',
'$prod_fob_unit','$prod_quantity','$prod_fob_value',
'$prod_gross_waight','$prod_cif_value','$prod_net_weight',
'$prod_cif_unit_price','$prod_brand','$hs_code','$shipping_date',
'$customs','$transport_company','$country_of_origin',
'$transport_mode','$country_of_trade',
'$hs_code_description','$product_description')";
mysql_query($insertquery)or die('ErrorrPERU: '.mysql_error());
/*$del="DELETE * FROM tb_excel_file";
mysql_query($del);*/
?>
This does not work, and gives the following error:
you have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
's','12U','6','9','54',
'34.83','55.5','31.83','6.17','','7323931000','2008/04/1' at line 3
Use mysqli_real_escape_string instead of deprecated mysql_real_escape_string
This function will force you to input mysql table / database.
This way your collation will be considered while escaping
You can use real_escape_string() in PHP. You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string). To add more, I'd say that you can also use PDO, but consider using addslashes($string) and stripslashes($string).

Read tab delimited text file into MySQL table with PHP

I am trying to read in a series of tab delimited text files into existing MySQL tables. The code I have is quite simple:
$lines = file("import/file_to_import.txt");
foreach ($lines as $line_num => $line) {
if($line_num > 1) {
$arr = explode("\t", $line);
$sql = sprintf("INSERT INTO my_table VALUES('%s', '%s', '%s', %s, %s);", trim((string)$arr[0]), trim((string)$arr[1]), trim((string)$arr[2]), trim((string)$arr[3]), trim((string)$arr[4]));
mysql_query($sql, $database) or die(mysql_error());
}
}
But no matter what I do (hence the casting before each variable in the sprintf statement) I get the "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" error.
I echo out the code, paste it into a MySQL editor and it runs fine, it just won't execute from the PHP script.
What am I doing wrong??
Si
UPDATE: Here are the echoe'd SQL's:
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A1', 'GBEN', '2.50-2.99m')
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A2', 'GBEN', '3.00-3.49m')
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A3', 'GBEN', '3.50-3.99m')
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A4', 'GBEN', '4.00-4.49m')
Interestingly, I now have it creating the correct number of rows in the table, but the values it inserts are empty...
Could this be an encoding issue in the source text file??
You don't need the string cast, the data will already be strings.
Make sure there are no quotes in the file data. Echo out the sql string before you run it to see if there's something obviously wrong.
Change the SQL to:
"INSERT INTO my_table (`field1Name`, `field2Name`, `field3Name`, `field4Name`, `field5Name`) VALUES('%s', '%s', '%s', '%s', '%s');"
This change includes the field names, and quoting the last two values.
I dont like you method in general. Maybe you fix your "first" problem with the missing
rows. Whats about some special character like '" backslash or SQL injection?
I think you should use prepared statements which PDO provides and call the "bindValue" of
the statement. It is a stable and buildin PHP lib. Or you can use dbTube.org instead
which is a graphical import tool.
Greeting
Shutter
From PHP.net:
<?php
fputcsv($fp, $foo, "\t");
?>
you just forgot that single quotes are literal...meaning whatever you put there that's what will come out so \t would be same as t because \ in that case would be only used for escaping but if you use double quotes then that would work.

Categories