upload image with other fileds into db - php

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?

Related

Why is my data not stripping properly with mysql_real_escape_string?

Here is my code below:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
//Finally, we can actually the field with the student's information
$sql = <<<SQL
UPDATE `database` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '{$studentTalking}',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
I am trying to use the mysql_real_escape_string to allow apostrophes entered into our form by the user to go to the database without breaking the database, however the data will either go through as null or the apostrophe will break the database. I have changed everything I could think of, and can't figure out why this isn't working. Yes I understand the that injections could break our database, and we will work on updating the code soon to mysqli but we need this working now. I suspect my syntax isn't correct and the first line may need to be moved somewhere, but I am not the strongest in PHP and I am working with code that was written by previous interns. Thank you in advance.
Switch to mysqli_* functions is the right answer.
The answer if intend to stayg with the deprecated and dangerous mysql_* functions:
Here you set a new variable equal to your escaped $_POST[]:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
But in your SQL you still refer to the $_POST array... Switch your SQL over to use your new variable you created
$sql = <<<SQL
UPDATE `tgtw_rsvp` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '$studentTalking',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
Because you are not using the stripped variable but still the raw POST data.

How to Save a image recieved via HTTP Post into mySQL

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 ) );

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

$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('{$mname}', {$pos}, {$vis}) ";
if(mysql_query($q)) {
header("Location: content.php");
}
else {
echo mysql_error();
}
Here, $mname is a string. $pos and $vis are integers.
Where is the mistake?
try to use only single quote to query variable rather pseudo(i think pseudo variable needs to be also quoted for query) like
$q= "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis')";
If you're going to use braces to try and prevent the greedy nature of variable expansion, you should use them properly.
The string "{$pos}", when $pos is 42, will give you "{42}", which is clearly not a valid integer in terms of your SQL statement. What you're looking for is instead:
${pos}
In this case, of course, you don't actually need the braces since the characters following the variable name cannot be part of a variable name - they are, respectively, ', , and ).
You only need to use braces when the following character could be part of a variable name. For example, consider:
$var = "pax";
$vara = "diablo";
In that case, $vara will give you diablo while ${var}a will give you paxa.
And I give you the same advice I seem to give weekly here :-) If you have a query that's not working, print it out! You'll find that the problem will usually become immediately obvious once you see the query in the final form you're passing to the DBMS.
And, as per best practices, I'll advise against using this method of creating queries. Anyone that's investigated SQL injection attacks (google for sql injection or, my favourite, little bobby tables) soon learns that they should use parameterised queries to prevent such attacks.
you are missing ' sign as the error says.
$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis') ";
The value will be stored to table. Just make datatype to int in mysql table if you want it to be integer and make validation not to enter string while inserting.
You cannot name a column name whenever you run something through MySQL. One way to check is to run the query within HeidiSQL. MySQL functions will be highlighted blue, so you know if the column name becomes blue to not use it. Also; Here's a quick run of PDO to make things a little bit better; I'd suggest looking further into it as well.
public function MakeMenu() {
$q = <<<SQL
INSERT INTO subjects (menu_name,_position,visible)
VALUES(":menu_name","_position","visible")
SQL;
$resource = $this->db->prepare( $query );
$resource->execute( array (
'menu_name' => $_POST['menu_name'],
'_position' => $_POST['position'],
'visible' => $_POST['visible'],
));
}
To make things easy enough you can just make a call.php page as well. Make the calls.php page require your class page and add a hidden input to your form. IE
<input type=hidden" id="process" value="make_menu">
Then within the calls.php page add
if ( isset($_POST['process']) )
{
switch ($_POST['process'])
{
case 'make_menu':
$class->MakeMenu();
break;
I know this isn't just a quick answer, but I'm hoping you'll look further into what's happening here and move away from mysql functions. I have seen posts from people running IIS servers and not having any luck with any of the deprecated functions. Not sure how long it will be until Apache follows suite, but don't waste your time with something that's being deprecated as we speak.

my sql query doesn't insert anything, what am i doing wrong?

i'm trying to insert a query into a database, however for some reason it's not working, perhaps you guys can see something i don't.
i know the enrties is right (as the checking bit does work on another page and so does the db selection.
it's starting to drive me nuts by now, and so is my project mate.
the query is used in PHP, after having filled a form. (on a different page).
$insert_query = "INSERT INTO enrties(
datum,
naam Relatie,
ContactPersoon,
bezoekreden)
VALUES (
'$_SESSION[Datum]',
'$_SESSION[RelatieNaam]',
'$_SESSION[ContractPersoon]',
'$_SESSION[redenBezoek]')";
mysql_query($insert_query);
my thanks in advance.
p.s: i'm using php my admin
EDIT: none of them did the trick, but i solved it because there was a , to much somewhere else >.<
naam Relatie is not a valid field name. Field names must be a single word, or escaped to "hide" the space. Beyond that, fieldnames with spaces in the name are bad practice, and as you can see, are VERY prone to causing just such problems.
$insert_query = "
INSERT INTO enrties
(`datum`,`naam Relatie`,`ContactPersoon`,`bezoekreden`)
VALUES ('$_SESSION[Datum]','$_SESSION[RelatieNaam]','$_SESSION[ContractPersoon]','$_SESSION[redenBezoek]')";
mysql_query($insert_query);
You should wrap field names in ` , and strings in '
mysql_error() will probably point you in the right direction as others have said.
Another point to note is that you shouldn't have array elements directly in your strings without enclosing them in curly braces, and field names with spaces in them should be enclosed in backticks.
My best guess for why it is failing though is that you have spelled the table name wrong. It should probably be "entries".
I would try this:
$insert_query = "INSERT INTO `entries` (`datum`,
`naam Relatie`,
`ContactPersoon`,
`bezoekreden`)
VALUES (
'{$_SESSION['Datum']}',
'{$_SESSION['RelatieNaam']}',
'{$_SESSION['ContractPersoon']}',
'{$_SESSION['redenBezoek']}')";
mysql_query($insert_query) or die(mysql_error());
you cannot have a field name with space so change naam Relatie to naam_Relatie that might can help you

PHP Query to Insert Variables into MySQL not working

The query below is not inserting the variables into MySQL. I know that the function valid_email2 works because I put a non-email address into $inviteeemail and it redirected per the code below.
I know that I have the right MySQL connection string.
Any idea why nothing is being put into MySQL?
$invitorname = $_POST['invitorname'];
$inviteename = $_POST['inviteename'];
$inviteeemail = $_POST['inviteeemail'];
$uid = $_POST['uid'];
$subcheck = (isset($_POST['subcheckinvite'])) ? 1 : 0;
if ( ! valid_email2($inviteeemail))
{
session_write_close();
header("Location:http://www...com/.../file.php");
exit;
}
else
{
mysql_query("INSERT INTO invites VALUES (NULL, '$uid', '$inviteeemail', '$invitorname', '$inviteename', NULL, '$subcheckinvite', NULL)");
}
In your query you have $subcheckinvite but you're setting it as $subcheck at the beginning of your script. Maybe that's it.
Does the fields that you insert NULL for, can be null?
Check the return value of mysql_query. If it is false, then the query was not valid, and you can print mysql_error() to see the error message.
It's not unlikely that this stems from the fact that you're not escaping any of the user input. Aside from allowing someone to completely change your query by carefully crafting the form inputs, your query will simply fail if any of the fields contain a single quote mark.
Besides fixing your error, you should consider improving the quality of your code.
You use variables that don't exist ($checksubinvite)
You insert NULLs into columns rather than simply specifying which columns you do want to insert into
You do not validate all of the inputs
You have single quotes around what are likely numeric columns
You have enormous amounts of whitespace and inconsistent indentation
...etc.

Categories