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

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

Related

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.

INSERT INTO sql query is using variable string rather than field name

Getting really confused surrounding this INSERT INTO. It should insert three fields into the table, userID, activateKey and isActivated.
The activateKey is a 25 letter randomly generated key such as 63n20kw24ba1mlox34e8n2awv
The userID comes from another table and is set by auto_increment.
The isActivated is always 0 at this stage.
It seems like quite a simple INSERT statement
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
{
echo("Error description: " . mysqli_error($con));
}
However it doesn't work when I include the $activateKey field. What it does is try to search the string variable $activateKey as a column name. The error I get is:
Error description: Unknown column '63n20kw24ba1mlox34e8n2awv' in 'field list'
Of course there is no such column as 63n20kw24ba1mlox34e8n2awv, this is the data I'm trying to insert, hence why it's in the VALUES section. Any ideas why it's trying to search this as the column name?
Edit to clarify: the var is activateKey, the column name is activationKey
I would put the query in a different variable to avoid confusion, and PHP automatically substitutes variable names in strings in double quotes.
Try this:
<?php
$query = "INSERT INTO activations (userID,activationKey,isActivated) VALUES($userID,'$activateKey','0')
if (!mysqli_query($con,$query)
{
echo("Error description: " . mysqli_error($con));
}
You are not surrounding the values with quotes, that's why they get interpreted as variable names.
Use single quotes, like this:
"INSERT INTO activations (userID,activationKey,isActivated) VALUES
('".$userID."','".$activateKey."','0')"
However, be aware that stringing together query strings exposes you to SQL injection attacks, if that's a concern in your code you should use parameterized queries. In fact, using parameterized queries is always better.
Change your query to this:
"INSERT INTO activations
(userID,activationKey,isActivated)
VALUES ('$userID','$activateKey','0')"
You dont need to use the concatenation (.) operator as variables will be interpolated into the string.
The single quotes tell mysql to treat the variables as literals instead of column names.
As a side note you would be better to use parameterized queries. See How can I prevent SQL injection in PHP?
Solved!
It was a case of not properly wrapping the dynamic fields (the vars in the VALUES section) in ticks:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES ('".$userID."','".$activateKey."','0')"))
Instead of
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
Might be a difficult one to spot. The variables still need to be 'in ticks' or they won't register as strings.
As activationKey is a string column, you must use single quotes for $activationKey.
Try with:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated)
VALUES (".$userID.",'".$activateKey."','0')"))

How to insert a space between two values in MySQL

My code:
$new_user= mysqli_query($db,"INSERT INTO userinfo (id,firstname,lastname,email,pass,displayname) VALUES ('','$fname','$lname','$email','$db_pass','$fname$lname')");
What I want to do:
as you can see in the end of the script that variable fname & variable lname are supposed to be both inserted in one column, but what I want is a space between those two values.
Explanation:
$fname=test;
$lname=tested;
I want it inserted in MySQL column like this: test tested
Instead, it inserts the values without a space, like this: testtested
What I've tried:
(....,'$fname.$lname').... Out comes: test.tested
(....,'$fname''$lname').... Out come: test'tested
Help me out please?
You literally just need a space between $fname and $lname, like $fname $lname. So, your whole code should look like this:
$new_user= mysqli_query($db,"INSERT INTO userinfo (id,firstname,lastname,email,pass,displayname) VALUES ('','$fname','$lname','$email','$db_pass','$fname $lname')");
Also, as #FreshPrinceOfSO says, you should use prepared statements. You have a potential SQL injection problem right now.

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?

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