INSERT Query Syntax Error in PHP and MySQL - php

I am not able to insert id and name in myTable MySQL table by using following PHP syntax. id is integer field and name is varchar field.
$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", ".$_SESSION["name"].");";
Is there something wrong with above syntax? As per me its right because if insert hardcoded values, those are inserted fine.

Yes, you need to use single quotes for name
$query="INSERT INTO myTable (id, name) VALUES (" . $_SESSION["id"] . ", '" . $_SESSION["name"]."');";
Also, please try not to contstruct the queries by hand using string concatenation/substitution. It can be dangerous if your $_SESSION (somehow) contains content that can manipulate queries completely.
Read about SQL Injection, and what PHP offers.

Put the string value inside quotes:
$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";

String should be enclosed in quotes
$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";

name is a reserved word. Put backticks around it. Also, you need quotes around your name variable (and the id, if it is not an integer).
Your query should look like this:
$query="INSERT INTO myTable (id, `name`) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."')";

use this
$query="INSERT INTO myTable (id, name) VALUES ({$_SESSION["id"]},'{$_SESSION["name"]}');";

Related

Mysql database insert with user input variable

The below code entered into the database:
"INSERT INTO customer_order (price) VALUES (1)";
Instead of VALUES (1), however, I want the value to be determined by user input.
Like this:
"INSERT INTO customer_order (customer_id) VALUES (".$edit_type.")";
This does not work, however, and does not return an error.
here you are using double code inside double code
try this :
"INSERT INTO customer_order (customer_id) VALUES ($edit_type)";

INSERT query not working in mysqli

I have a table named user_data which contains 5 rows-id(primary key),name,address,phone,sex.When I try to insert values into the table via this query
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
it doesnt work.But When I tried this one,it works.
mysqli_query($con,"INSERT INTO user_data (name,address,phone,sex) VALUES ('Peter_Gregory', 'Griffin door',35897,'male')");
I didnt understand what is the real issue behind this.I am using PHP 5.4.7 and XAMPP 1.8.1.
instead of this:
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
Use this when the field is set as NOT NULL
mysqli_query($con,"INSERT INTO user_data VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male')");
Or use this when the field is set as NULL
mysqli_query($con,"INSERT INTO user_data VALUES (0, 'Peter_malik', 'Griffin door',35897,'male')")
See the mysql manual: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
It does not insert in the first query since it assumes the first value i.e. 'Peter_malik' is for your primary key and it fails.
When you specify the column names in the query it knows which value is for which column.
I addition in the first case i.e.
'Peter_malik', 'Griffin door',35897,'male'
will refer to
id(pk),name,address,phone
So u need to pass the first value as NULL so that id gets auto incremented. So the first query should be as
VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male')
If your table has 5 columns id, name, address, phone and sex your staement has to provide 5 values, one for each column. Since your stament provides only 4 values, you need a column list to tell MySQL which values you do provide.
If your id column is a auto_increment column, you can provide null in your values clause.
So you have to say:
INSERT INTO user_data VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male');
OR
INSERT INTO user_data (name,address,phone,sex) VALUES
('Peter_malik', 'Griffin door',35897,'male')
You need to include the id column on your insert statement:
mysqli_query($con,"INSERT INTO user_data VALUES (null, 'Peter_malik', 'Griffin door',35897,'male')");
, provided that your id field is set to autoincrement! ;)
If you provide the ID also in your first query, it will work without any problem.
Assuming that id=1
mysqli_query($con,"INSERT INTO user_data VALUES (1,'Peter_malik', 'Griffin door',35897,'male')");
As others said when you have not explicitly mentioned your column names in a query, you have to provide all the values.
when you are trying the following query then...
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
In this query you only inserting 4 values in the table but the table has 5 field so it is causing problem because in the above query the value is inserting form first field & the sequence or datatype mismatching in the database because of this this query causing problem .
If u want insert wuthout specifing field then you may use the following query....
mysqli_query($con,"INSERT INTO user_data VALUES (0,'Peter_malik', 'Griffin door',35897,'male')");<br><br>
It Will work properly.
and in the your second query you also specifying the field name & corresponding their values so that's query not causing any problem.

Insert statement not updating without ID

I am doing an ajax to write records into the db. The table has id,fullname. The id is set to primary and auto increment. Now without the id (8 in the below statement) the record is not written.
Below is the insert statement
$sql =
"INSERT INTO user
VALUES ('8','".$_POST['name']."','test4','test5','test6')";
Is it possible to write without the id?
Place NULL instead of '8', that will tell MYSQL to do default auto increment:
$sql="insert into user values (NULL,'".$_POST['name']."','test4','test5','test6')";
Other possibility is to rewrite your query to this from:
$sql="insert into user (field1, field2, field3, field4) values ('".$_POST['name']."','test4','test5','test6')";
In this case you didnt specify id as a column to be inserted, so MySQL will again do the default auto increment
You can also omit the ID column in the query so that It automatically increments the ID Value
Yes it's totally possible but you need to specify which columns you are inserting into... for example:
$sql="insert into user (username, column2, column3, column4) values ('".$_POST['name']."','test4','test5','test6')";
Try
$sql="insert into user values (NULL,'".$_POST['name']."','test4','test5','test6')";
or
$sql="insert into user(`field1`, `field2`, `field3`, `field4`) values ('".$_POST['name']."','test4','test5','test6')";
You can use DEFAULT or NULL instead of '8'
insert into user(DEFAULT, column1, column2, column3) VALUES (....

PHP ~ Column count doesn't match value count at row 1

I'm creating a registration and I'm using just straight PHP not JavaScript to send my form to the MySQL database, so everything is working fine, no syntax error or anything but I fill out all my information and click 'Register' and it returns a message saying 'Column count doesn't match value count at row 1'.
I'm only 14 so this is pretty confusing for me does anyone have a solution?
This is my INSERT INTO code:
$sql = mysql_query("INSERT INTO users(firstname, lastname, email, password, day, month, year, gender)
VALUES('$firstname','$lastname','$email','$db_password','$day','$month','$year')")
or die (mysql_error());
You are trying to insert 7 values into 8 columns - you are missing the insertion of gender.
The correct code would be:
$sql = mysql_query("INSERT INTO users(firstname, lastname, email, password, day, month, year, gender)
VALUES('$firstname','$lastname','$email','$db_password','$day','$month','$year', '$gender')")
or die (mysql_error());
By the way, if you are not already doing it, I highly recommend escaping the strings first, before passing them to the query like so:
$firstname=mysql_real_escape_string($firstname)
You should do this with all variables above. Here you can find more about the escape function.
With your code there, I see you forget to insert $gender.
When inserting data into a MySQL table, you will have to specify which data goes into which column. You do this by specifying the column names before the VALUES part:
INSERT INTO tblA (col1, col2) VALUES ('value1','value2');
If you omit that information, MySQL will expect all columns:
If your table is like this:
CREATE TABLE tblA (
col1 INT,
col2 INT
);
You can insert information like this:
INSERT INTO tblA VALUES ('value1', 'value2');
If you omit column names and do no specify values for all columns, MySQL will give the "Column count doesn't match value count at row" error will occur, as MySQL doesn't know what to put in the missing columns. With the table structure as above,
INSERT INTO tblA VALUES ('value1');
will result in that error.
In non-strict mode, MySQL will insert default values for omitted column names.
You have missed a value for gender column (the last one)
You are completely missing the gender value:
$sql = mysql_query("INSERT INTO users(firstname, lastname, email, password, day, month, year, gender)
VALUES('$firstname','$lastname','$email','$db_password','$day','$month','$year', 'gender goes here')")
or die (mysql_error());

Getting an SQL syntax error

I have a line of code in PHP as follows...
mysql_query("INSERT INTO `updates` (project_id, date, update) VALUES ('{$project}', '{$date}', '{$update}')") or die(mysql_error());
However I'm getting the following SQL syntax 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 'update) VALUES ('14', '2012-05-06', 'Test update')' at line 1
If anyone could help me with this that would be great, perhaps it's obvious but I just can't see what's wrong here!
Change the query as below:
mysql_query("INSERT INTO `updates` (`project_id`, `date`, `update`) VALUES ('{$project}', '{$date}', '{$update}')") or die(mysql_error());
This is because date and update are registered keywords in MySQL. We cannot use it directly in the query. We need to escape it.
date and update are reserved words in MySQL.
You can use:
"INSERT INTO `updates` (project_id, `date`, `update`) VALUES ('{$project}', '{$date}', '{$update}')"
Though ideally you should never use a reserved word as an entity name. It offers no advantages, yet has a few minor disadvantages (for example, makes the SQL less portable).
Also, a fairly minor point, if project_id is an integer typed field, pass it an integer, not a string. Like:
INSERT INTO `updates` (project_id, `date`, `update`) VALUES ({$project}, '{$date}', '{$update}')
update is a keyword in SQL, encapsulate your mysql fields in backticks.
First and foremost Thing: you can not user mysql preserver word. When you use it, be ready to waste your hours in finding out error.
Here is the list of reserve words: DO NOT USE ANY AMONG IT
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Second: Even if you want to dare to use preserved keyword. User table prefix or column prefix along with reserved keyword.
Third:
When ever you perform the database operations along php either quote each and every parameter where required or just user simple one.
i.e if you wish to quote db table columns than surround each column by quote
"INSERT INTO `updates` (`project_id`, `date`, `update`) VALUES ('{$project}', '{$date}', '{$update}')"
and if you don't quote then quote none of them
"INSERT INTO updates (project_id, date, update) VALUES ('{$project}', '{$date}', '{$update}')"
Hope this would help you

Categories