How to Save a image recieved via HTTP Post into mySQL - php

I want to write an image received via http into my database using PHP. I access the image with
$inputImage = file_get_contents('php://input');
Echoing the $inputImage works fine, so the transport to the server doesn't seam to be a problem.
I now tried to insert the image with
$sqlRequest="INSERT INTO Image(time, data) SET (NOW(), '$inputImage')";
mysqli_query($connection, $sqlRequest) or die("Error in Inserting " . mysqli_error($connection));
But it doesn't work and i recieve the following error
Error in Inserting 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 'SET (NOW(), '����' at line 1
Can someone give me a hint
thanks
edit:
okay changed the sytax problem, got to look for the blob problem

Use VALUES() instead of SET(). SET is meant for updating (using UPDATE) whereas VALUES() is meant for inserting (using INSERT).
See this for INSERT syntax and this for UPDATE syntax.

Looking at the funny characters ����, this sounds like you're trying to upload a binary file into a column that isn't capable of handling that type.
Sidenote edit: seeing your comment now, you still need to escape that variable.
By "escape", I mean that you need to use mysqli_real_escape_string().
If this isn't set, then you will need to ALTER your column to either be a BLOB or LONGBLOB.
More importantly, you need to escape the contents of $inputImage because that will be binary data and could contain bytes that will cause MYSQL to assume it is shorter than it actually is.
$inputImage = mysqli_real_escape_string($connection, $inputImage);
$sqlRequest="INSERT INTO Image(time, data) VALUES (NOW(), '$inputImage')";
And of course as I already stated in comments under your question, you're using the wrong syntax in your query.
Use VALUES() and not SET().
Add or die(mysqli_error($connection)) to mysqli_query() also.
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
Using a prepared statement would also work:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

you want to make sure no data obstructing your sql string is stored so do this:
$inputImage = base64_encode(file_get_contents('php://input'));
before storing the data and then
$myImage = base64_decode( myGetImageFromDBFunction( $myImageID ) );

Related

Proper mySQL command for adding URLs

I'm having a problem when trying to add a URL to a mySQL database.
The string is a URL:
http://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_8645107_703731598_n_normal.jpg
The error I get is:
Error description: 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 '://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_86' at line 1
It seems as though it won't allow me to add a URL, I presume there is something wrong with some of the characters but I don't know what?
My SQL is:
INSERT INTO accounts (name,consumerkey,consumersecret,pic_url) VALUES ($twitterID,$consumerkey,$consumersecret,$picture_url)"
You cannot truly solve this kind of problem by adding a few characters (like ' or ") to your bespoke sql string!
Instead, get to know the real way to write sql in php (it's like a very badly kept secret), which is to use PDO statements. This will allow you to use placehoders like (:twitterID, :consumerKey, :consumerSecret, :pictureUrl) which will accept complex variables such as urls and any of the crap users send in much more gracefully.
In the long run, this will save you a lot of trouble and time.
You need to quote string values and any other character that SQL will complain about, in this case it's the colon; see further down below.
($twitterID,$consumerkey,$consumersecret,'$picture_url')
or
('".$twitterID."','".$consumerkey."','".$consumersecret."','".$picture_url."')
if you wish to quote all the values.
Sidenote: You can remove the quotes around the variables that are integers.
I.e.:
This based on, and without seeing how the rest of your code looks like:
$picture_url = "http://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_8645107_703731598_n_normal.jpg";
The error states that it is near : - near being just that, the colon.
...right syntax to use near '://pbs.twimg.com
^ right there
You can also use:
VALUES ($twitterID, $consumerkey, $consumersecret, '" .$dbcon->real_escape_string($picture_url) . "')";
$dbcon is an example of a DB connection variable and based on mysqli_ syntax.
Something you haven't stated as to which MySQL API you are using.
Plus, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements.

how to insert a buffer data to mysql in php

I want to store the $newreg buffer data to mysql database. I tried with text and BLOB in mysql, but it returns 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 '179' height='100' />',2)' at line 1
Or is there any other way to do this?
ob_start();
echo("\n<div class='templadf_section_2'>");
echo("<img src=$tprofpic1 alt=$description />");
echo("<h4>For sale at $district</h4>");
echo("<p>$description</p>");
echo("<div class='price'>PRICE:<span> $expectedprice INR</span></div>");
echo("<div class='readmore'><a href=$tempath>Read more</a></div>");
echo("</div>");
$newreg=ob_get_clean();
Without seeing your mysql query I couldn't say for sure, but if I had to guess I would say you are not escaping the apostrophes in your query. Make sure you are running the data through mysql_real_escape_string() prior to running your queries.
As Dagon said, you should assign the string to $newreg instead of using output buffering. If it is spread out among the code user $newreg .= "string" to append more to the string. Using ob works, but it adds additional overhead and depending on your code could allow for unintended text to be added to the string
Other than what #CJ Wurtz's answer, I only see this solution: it seems that, You are either not using quotes for numeric value or Your input data isn't cleaned/escaped before use.
Try this
$newreg = mysql_real_escape_string(stripslashes(ob_get_clean()));
This will escape the single quotes in your string/entry.

upload image with other fileds into db

I want to store my values to db. Also I want to upload one image. My insert query is below. It's not working.
$query = mysql_query("insert into designingoption set name='$name1',positionCode='$pos',assetType='$ass',price='$price',createdOn='$createdon',lastModifiedOn='$laston',lastModifiedBy='$lastby')",$con);
Here name=$name is my image upload field..
Not sure whats not working, but, i gotta a pretty good idea the values are not inserted since you used ' (single quote) around $variables.
Try like this.
$query=mysql_query("insert into designingoption set name='".$name1."',positionCode='".$pos."',assetType='".$ass."',price='".$price."',createdOn='".$createdon."',lastModifiedOn='".$laston."',lastModifiedBy='".$lastby."')",$con);
You have mixed the syntax for the UPDATE and INSERT statements.
Correct syntax:
INSERT INTO designingoption ('name', 'positionCode', 'assetType', 'price', 'createdOn', 'lastModifiedOn', 'lastModifiedBy') VALUES ($pos, $ass, $price, $createdon, $laston, $lastby)
While you're at it, you might also want to consider switching to the mysqli-functions. The mysql-functions are deprecated.
Also be careful of SQL-injection. More information on the subject can be found here.
Update your query structure.
INSERT INTO designingoption (name,positionCode,assetType,price,createdOn,lastModifiedOn,lastModifiedBy) VALUES ('$name1','$pos','$ass','$price','$createdon','$laston','$lastby')
Also, make sure that all variables are populated, otherwise you get a PHP notice.
It wouldn't hurt to enclose table rows with `, like this:
INSERT INTO `designingoption` (`name`,`positionCode`,`assetType`,`price`,`createdOn`,`lastModifiedOn`,`lastModifiedBy`) VALUES ('$name1','$pos','$ass','$price','$createdon','$laston','$lastby')
Some words are reserved by the system and must be used properly, otherwise you just receive error.
A little research as revealed (even to my surprise) that your syntax is correct.
http://dev.mysql.com/doc/refman/5.5/en/insert.html
Would you please edit your question with exact error you're getting?

I have a SQL Syntax error on my php page

Here is the mysql insert the I am running in php. I have removed the part giving the error but then I get a error on the next piece. I am not seeing what is diffrent to cause the error.
$fields="adv_exchange SET synum='".$synum."', worknum='".$_POST['worknum']."', user_id='".$current_user->ID."', f_name='".$current_user->user_firstname."', l_name='".$current_user->user_lastname."', email='".$current_user->user_email."', regnum=".$_POST['regnum'].", item='".$item."', qsver='".$_POST['qsver']."', flashrom='".$_POST['flashrom']."',expansion='".$_POST['board']."', rdisplay='". $_POST['rdisplay']."', screen_model='".$_POST['screen_model']."', p_hardware='".$_POST['cable']."', pcolor='".$_POST['pcolor']."', pname='".$_POST['pname']."', kboard='".$_POST['kboard']."', ip='".$_POST['ip']."', reg_name='".$_POST['reg_name']."', mem=".$_POST['mem'].", dt_server='".$_POST['dt_server']."', alert='".$_POST['alert']."', ows='".$_POST['ows']."', w_date='".$_POST['w_date']."', flashromver='".$_POST['flashromver']."', s_size='".$_POST['s_size']."', mag='".$_POST['mag']."', rcard='".$_POST['rcard']."', kvsid=".$_POST['kvsid'].", finger='".$_POST['finger']."', stand_alone='".$_POST['stand_alone']."', standards='".$_POST['standards']."', profile='".$_POST['profile']."', man_date='".$_POST['man_date']."', l_sn='".$_POST['l_sn']."', misc='".$_POST['misc']."', problem='".$_POST['problem']."'";
then $query = "insert into $fields";
I receive back
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 ' item='JS900CV', qsver='', flashrom='',expansion='', rdisplay='', screen_model='' at line 1
Blockquote
if I echo the $query I get this:
insert into adv_exchange SET synum='SY5135', worknum='123456', user_id='2', f_name='REMOVED', l_name='REMOVED', email='REMOVED', regnum=, item='JS900CV', qsver='', flashrom='',expansion='', rdisplay='', screen_model='', p_hardware='', pcolor='', pname='', kboard='', ip='192.168.1.16', reg_name='', mem=, dt_server='', alert='', ows='', w_date='', flashromver='', s_size='', mag='', rcard='', kvsid=3, finger='', stand_alone='', standards='', profile='', man_date='', l_sn='', misc='misc test\r\n', problem='gen test'
Depending on what I enter in the error is changing spots in my statement. Not all fields are used the form is dynamic that is supplying the data so the fields are dependent on what options are selected. On a side note in case of concern about using $_POST to insert directly into mysql, I sanitize the array first. Any help would be greatly appreciated.
Look at regnum=,. You don't provide a value for regnum. Either leave it out entirely or set it to an appropriate value.
You're using a very, very bad approach to MySQL databases: manually creating the queries. You should really use prepared statements instead: this issue will be resolved as well.
Don't use mysql_* functions, use PDO instead.
Your code would look like this (simplified):
// This holds the query
$statement = $pdo->prepare('INSERT INTO adv_exchange SET synum=?, worknum=?, etc=?, problem=?');
// This executes it with the given arguments. It's 100% injection-proof and safe. In fact, it's also faster.
$statement->execute(array($synum, $_POST['worknum'], $_POST['therest'], $_POST['problem']));
regnum=".$_POST['regnum']." is causing the problem. When it is undefined, you get regnum=, in the SQL query
A bigger concern is that you are not escaping your inputs. Either use mysql_real_escape_string around them, or better, use prepared statements.
You need to SET regnum=SOMETHING.
Currently it's empty.

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#dt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BpbiBNSU1FIGZvcm1hdC4KCi0tLS0tLT1fTmV4dFBhcnRfMDAwXzAxMjlfMDFDNjlDNUUuQUZGMDdDNzAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOwoJY2hhcnNldD0iaXNvLTg4NTktMSIKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogcXVvdGVkLXByaW50YWJsZQoKdGhpcyBpcyBhIHRlc3QKLS0tLS0tPV9OZXh0UGFydF8wMDBfMDEyOV8wMUM2OUM1RS5BRkYwN0M3MApDb250ZW50LVR5cGU6IHRleHQvaHRtbDsKCWNoYXJzZXQ9Imlzby04ODU5LTEiCkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFibGUKCjwhRE9DVFlQRSBIVE1MIFBVQkxJQyAiLS8vVzNDLy9EVEQgSFRNTCA0LjAgVHJhbnNpdGlvbmFsLy9FTiI+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"

Categories