How to insert compressed data using PDO? - php

I'm trying to insert a large serialized object into a MySQL database using PDO. Attempting to insert directly gives:
PDOStatement::execute() [pdostatement.execute]: SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_packet_allowed' bytes
There seem to be a few possible ways to tackle this but my first tack is gzcompress, bringing it down from 2383731 to 155955 bytes (using compression level 6). But am now struggling to insert the result for a different reason:
PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'lob) VALUES ('[some binary data spued out here]'
Here's the basic gist of the code:
$value = gzcompress(serialize($lob));
$stmt = $conn->prepare("INSERT INTO saved (lob) VALUES (:value)");
$stmt->bindParam(':value', $value, PDO::PARAM_LOB);
$stmt->execute();
The examples in the documentation all seem to be using file streams rather than binary data stored in a string so am not sure this is valid. Could anyone advise?

The error sounds like you need to add backticks around the field name:
INSERT INTO saved (`lob`) VALUES (:value)

Related

inserting HTML with PDO

I am currently undergoing the process to convert my code from MySQL to PDO however I am having an issue passing a variable. I have edited the content of the variable to give you an idea of exactly what is happening.
$status = 'Pending';
$stmt = $db->prepare("INSERT INTO
cusbuilder_sites(userid,name,imgurl,url,explain,status,incustom) VALUES
(:userid,:campname,:imgurl,:targeturl,:explain,:status,:incustom)");
$explain = '<p>Testing Input</p>';
$stmt->bindParam(':userid', $username);
$stmt->bindParam(':campname', $_POST['campname']);
$stmt->bindParam(':imgurl', $_POST['imgurl']);
$stmt->bindParam(':targeturl', $_POST['targeturl']);
$stmt->bindValue(':explain', $explain, PDO::PARAM_STR);
$stmt->bindParam(':status', $status);
$stmt->bindParam(':incustom', $_POST['incustom']);
$stmt->execute();
Now this is the error I am getting:
: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'explain,status,incustom) VALUES ('myuserid','testing12','http://testingsite.com' at line 1'
As you can see the $explain variable contains HTML code and when I remove the p tags it works fine but I need it to actually store the HTML in the database as it did with MySQL.
I have read the answers to this question and have checked if magic_quotes or gpc are enabled. They aren't. In my previous code I was using mysql_real_escape_string which obviously I cannot use in PDO so I just want to know how do i pass HTML in a variable and insert it into a database using PDO?
For those who are going to answer 'use bindValue instead of bindParam' you will see I have already done this and the error is the same.
This doesn't have anything to do with HTML. The SQL query itself is invalid. explain is a reserved word. Enclose your identifiers in back-ticks (assuming MySQL, other characters may be used by other databases) to specify them as identifiers:
INSERT INTO `cusbuilder_sites`
(`userid`,`name`,`imgurl`,`url`,`explain`,`status`,`incustom`) VALUES
(:userid,:campname,:imgurl,:targeturl,:explain,:status,:incustom)

Insert image blob into mysql database from a mysql data row using PHP

I am using following Insert statement to insert Blob row read from one database into another. (there is data when i echo the same insert statement).
UPDATE:
"INSERT INTO co_registration_picture_evidence_blb
(_URI, _CREATOR_URI_USER, _CREATION_DATE, _LAST_UPDATE_URI_USER, _LAST_UPDATE_DATE,
_TOP_LEVEL_AURI, VALUE) VALUES('".$imageRow['_URI']."','".$imageRow['_CREATOR_URI_USER']."','"
.$imageRow['_CREATION_DATE']."','".$imageRow['_LAST_UPDATE_URI_USER']."','".
$imageRow['_LAST_UPDATE_DATE']."','".$imageRow['_TOP_LEVEL_AURI']."'".
$imageRow['VALUE']."')"
I get following error message.
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 3
Update: Now i get this 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 '?PNG\r\n\Z\n\0\0\0\rIHDR\0\0\0?\0\0\0?\0\0\0????\0\0%iCCPICC Profile\0\0x??M' at line 3
Can anyone tell what's wrong with the syntax? my guess is that i should wrap VALUE column that is of type LongBlob (that holds an image) to some encoding function. (all data fields are already mysql_real_escape_string() filtered).
Any input would be really appreciated.
Regards.
You seem to be missing a , '
INSERT INTO co_registration_picture_evidence_blb
(_URI, _CREATOR_URI_USER, _CREATION_DATE, _LAST_UPDATE_URI_USER, _LAST_UPDATE_DATE,
_TOP_LEVEL_AURI, VALUE) VALUES('".$imageRow['_URI']."','".$imageRow['_CREATOR_URI_USER']."','"
.$imageRow['_CREATION_DATE']."','".$imageRow['_LAST_UPDATE_URI_USER']."','".
$imageRow['_LAST_UPDATE_DATE']."','".$imageRow['_TOP_LEVEL_AURI']."', '".
$imageRow['VALUE']."')
What did I change?
'".$imageRow['_TOP_LEVEL_AURI']."'".
'".$imageRow['_TOP_LEVEL_AURI']."', '".

PDO fetch statement issues

I have the below PHP for my book keeping application. It uses PDO.
if (isset($_POST['lesson'])AND isset($_POST['page']))
{
try {
$options_pdo[PDO::ATTR_ERRMODE]=PDO::ERRMODE_EXCEPTION ;
$DB= new PDO('mysql:host=localhost;dbname=mydb','jamie','admin',$options_pdo);
$statement=$DB->query("SELECT data FROM teach_books where lesson=".$_POST['lesson']."AND page=".$_POST['page'] );
while($results = $statement->fetch()){
$results['data'];
echo "<br>";
}
} catch(Exception $e) {
die ('ERROR: '.$e->getMessage());
exit;
}
}
However when I run the code it displays the below error:
ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'page=dsas' at line 1
Could anybody help please?
A couple of things:
1) DO NOT INSERT RAW QUERY STRINGS:
This code is extremely suseptable to SQL Injection. PDO has a feature called 'prepared statements'. This is waht you should be using for you SQL queries. Do not just inject some POST parameters into the query string as the result will be a security hole. The quotes you have accidentally inserted into the query may well have come from a malicious user trying a SQL attack.
2) MISSING SPACE:
You have a missing space right before the AND. The parser does not know what to make of the term 2AND and so produces the error. The SQL by iteslf expands to something like.
SELECT data FROM teach_books where lesson=2AND page=24;
3) MISSING QUOTE MARKS:
If you were to use something like the above you will need to add some closing quote marks at the end of the query. You also need quotes around the string params that you give inside the select.
4) ECHO DATA:
You are not actually printing out anything in the loop. Simply having a statement sitting inside PHP will not print it out. You need echo command.
echo $results['data'];
5) ITERATE OVER OBJECT:
You do not need to keep calling fetch(), you could use fetchAll() and then iterate over that result set.
Really you should not call any "fetch" method unless you just need the rows in an array.
The result set object is iterable and can be looped over.
$statement->execute();
foreach ($statement as $row) {
...
}
6) TRY-CATCH:
You could probably remove the 'try-catch' code because what you are doing inside there is what the exception would do anyway.
Additionally I hope 'admin' is not your actual password.
Sorry to have kept adding to my answer. Just wanted to post the 6 points by themselves and then expand on them.
Hope that helps
Your SQL are wrong, try it:
$statement=$DB->query("SELECT data FROM teach_books where lesson='".$_POST['lesson']."'AND page='".$_POST['page']."'" );
You'r comparing string values, so you need to use '' on sql query.
ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'page=dsas' at line 1
The problem is probably becaus you didn't add quotes for the value:
".... page='".$_POST['page']."'"
Strings ALWAYS need quotes around them.

MySQL insert with mbox format

Maybe it's my query, but I don't think so. I'm attempting to import messages parsed from an mbox format into MySQL, but MySQL fails when I do it through PHP or manually through phpMyAdmin. Any thoughts?
$sql='INSERT INTO `listserv_mbox` ("message-id", "mbox")
VALUES ("'.mysql_real_escape_string($structure->headers['message-id']).'"
,"'.mysql_real_escape_string($message_base64).'")';
// Run our MySQL query
$db->Execute($sql);
This code looks correct to me, so I'm totally lost on why I cannot import this data for whatever reason. The error I keep getting is:
1064: 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 '"message-id", "mbox") VALUES ("<012c01c69c88$98e38250$31780b4b#dtadavid>","RnJvb' at line 1
The query looks like this. I couldn't get it to work before, so I decided to try base64_encode() on the message itself, but still it doesn't work. Here's the base64_encod()'d query.
INSERT INTO `listserv_mbox` ("message-id", "mbox")
VALUES ("<012c01c69c88$98e38250$31780b4b#dtadavid>"
,"RnJvbSBkYXZpZC53YWxsaXNAZHRhaG91LmNvbSBGcmkgSnVuIDMwIDE1OjA3OjQyIDIwMDYKUmVjZWl2ZWQ6IGZyb20gbWFpbC5kdGFob3UuY29tIChtYWlsLmR0YW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vLTg4NTktMSIKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogcXVvdGVkLXByaW50YWJsZQoKdGhpcyBpcyBhIHRlc3QKLS0tLS0tPV9OZXh0UGFydF8wMDBfMDEyOV8wMUM2OUM1RS5BRkYwN0M3MApDb250ZW50LVR5cGU6IHRleHQvaHRtbDsKCWNoYXJzZXQ9Imlzby04ODU5LTEiCkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFibGUKCjwhRE9DVFlQRSBIVE1MIFBVQkxJQyAiLS8vVzNDLy9EVEQgSFRNTCA0LjAgVHJhbnNpdGlvbmFsLy9FTiI+CjxIVE1MPjxIRUFEPgo8TUVUQSBodHRwLWVxdWl2PTNEQ29udGVudC1UeXBlIGNvbnRlbnQ9M0QidGV4dC9odG1sOyA9CmNoYXJzZXQ9M0Rpc28tODg1OS0xIj4KPE1FVEEgY29udGVudD0zRCJNU0hUTUwgNi4wMC4yOTAwLjI5MTIiIG5hbWU9M0RHRU5FUkFUT1I+CjxTVFlMRT48L1NUWUxFPgo8L0hFQUQ+CjxCT0RZIGJnQ29sb3I9M0QjZmZmZmZmPgo8RElWPjxGT05UIGZhY2U9M0RBcmlhbCBzaXplPTNEMj50aGlzIGlzIGEgPQp0ZXN0PC9GT05UPjwvRElWPjwvQk9EWT48L0hUTUw+CgotLS0tLS09X05leHRQYXJ0XzAwMF8wMTI5XzAxQzY5QzVFLkFGRjA3QzcwLS0=")
INSERT INTO `listserv_mbox` ("message-id", "mbox"
That should be
INSERT INTO `listserv_mbox` (`message-id`, `mbox`
` instead of "
Maybe value is just too long for type of field "message_id"

Yii Framework/PDO getting error CDbCommand failed to execute the SQL statement: SQLSTATE[42000]

I'm trying to insert some data into a table using the Yii Framework together with the PDO object and get the following error
I'm building the query using this code
$connection = CActiveRecord::getDbConnection();
$sql="INSERT INTO sms_logs (to, from, message,error_code,date_send) VALUES (:to,:from,:message,:error_code,:date_send)";
$command=$connection->createCommand($sql);
$command->bindParam(":to",$to,PDO::PARAM_STR);
$command->bindParam(":from",$from,PDO::PARAM_STR);
$command->bindParam(":message",$message,PDO::PARAM_STR);
$command->bindParam(":error_code",$code,PDO::PARAM_STR);
$command->bindParam(":date_send",date("Y-m-d H:i:s"),PDO::PARAM_STR);
$command->execute();
And then as soon as I run the code I get
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'to, from, message,error_code,date_send) VALUES ('27724963345','27723663542','Hap' at line 1INSERT INTO sms_logs (to, from, message,error_code,date_send) VALUES (:to,:from,:message,:error_code,:date_send)
any suggestions will be welcome! using mySql as the db
You need to escape the word from in your $sql. It is a reserved word.

Categories