auto increment id not inserted - php

I am using simple MySQL code to insert data from a form with auto_increment id, it works fine on local host but not on server.
this is the code I am using
$myvar=$_POST['var'];
//Insert data into mysql table
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
in local host phpmyadmin data is inserted in table but on server phpmyadmin data is not inserted in table. In my localhost I am using XAMPP whereas phpmyadmin on IIS server.
What setting should I do in phpmyadmin on server so that id is automatically inserted with auto increment, I know I can use mysql_insert_id() to insert id but in lots of file i have used this type of code which I cannot change. I want the same setting as XAMPP that can take this type of code easily.

You as inserting '' into auto-increment id. just insert other fields and MySQL handles the auto-increment column.
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
should be
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";

if still you are getting the error
first check, in the server your id column must marked as auto_increment.data type should be int.
if it is ok then
insert into mytable(myvar) values('test');
and try to use prepared statements to avoid the sql injection. Thanks.
hope this may usefull for you.

If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! :) kind of.
SELECT fields FROM mytable BY id DESC LIMIT 1;
will get the last id then increment it to 1 // add this value to id in insert statement
or
if you have a autoincrement column change it to
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
to
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";

auto increment inserts id itself so you don't need to pass it through code
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
or you can do this
$sql="INSERT INTO mytable(id,myvar) VALUES (NULL,'$myvar')";
if you want want to manually insert id for some reason
$sql="INSERT INTO mytable(id,myvar) VALUES (10,'$myvar')";

First check your table Structure Property by applying query:
desc mytable (or) show create table mytable.
Check auto increment property been set for column id.
If yes means don't need to pass id in insert query.
Just write a query as :-
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";

Related

error in insert sql statement

this is sign up form pls help me to solve this error
ERROR: Could not able to execute sql insert statement
INSERT INTO customer(customer_id,customer_name,customer_email,customer_password) VALUES (null,'','','').Column 'customer_id' cannot be null
//check connection
if($link===false){
die("ERROR: could not connect. " . mysqli_connect_error());
}
//Escape user inputs for security
$customer_id = mysqli_real_escape_string($link, $REQUEST['customerid']);
$customer_name = mysqli_real_escape_string($link, $REQUEST['Name']);
$customer_email = mysqli_real_escape_string($link, $REQUEST['Email']);
$customer_password = mysqli_real_escape_string($link, $REQUEST['Password']);
//attempt insert query execution
$sql="INSERT INTO customer(customer_id,customer_name,customer_email,customer_password) VALUES (null,'$customer_name','$customer_email','$customer_password')";
if(mysqli_query($link,$sql)){
echo "records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql.".mysqli_error($link);
}
mysqli_close($link);
?>
It says in your error message that the column customer_idcan not be null.
Looking at your query VALUES (null,'$customer_name','$customer_email','$customer_password')"; the values start after the parenthesis. So your first column is customer_id and the first value is null.
The error message tells you that your table is not setup to allow for customer_id to be null. So you either have to change to database table structure or your query. As it is about an ID I suggest you change your query.
If customer_id is an auto incremented field you should simply not set it (remove it from your query)
Edit:
It is not usual to have an identifier set to varchar. Seeing something like customer_id lets most people assume that they are dealing with an integer. The easiest approach would be to make that table column an integer with auto increment in your database (in most cases such a field would also be primary key).
Seeing that your table requires the field customer_id it can not be left out from your query and you would have to generate / create an adequate identifier for your customer. A workaround for your current table structure:
$sql="
INSERT INTO
customer
(customer_id,customer_name,customer_email,customer_p‌​‌​assword)
VALUES (
(select count(customer_id) from customer)+1,'$customer_name','$customer_email','$customer_pa‌​ssword‌​')";
Edit 2:
Some additional information on database column data types: mysql char vs. varchar and mysql integer
if you later on have a more complex database and query multiple tables at once to gather your data you will have to rely on your indices and realtions (foreign keys) to get the results fast. IE: having a join on your customer_id is rather slow. setting it to char lets it operate faster due to varchar having a variable length. I have not yet tested the performance regarding char and integer
You need to pass customer_id instead of null in the query, e.g.:
$sql="INSERT INTO customer(customer_id,customer_name,customer_email,customer_password)
VALUES ('$customer_id','$customer_name','$customer_email','$customer_password')";
You can remove customer_id column like below,
$sql="INSERT INTO customer(customer_name,customer_email,customer_password)
VALUES ('$customer_name','$customer_email','$customer_password')";
If you set customer_id as auto increment in database there no need to include it in query
If your customer_id is an autoincrement id of your customer table then, no need to put it inside your INSERT statement.
Simply run without customer_id
$sql="INSERT INTO customer(customer_name,customer_email,customer_password)
VALUES ('$customer_name','$customer_email','$customer_password')";
Ok. Let me explain you somethings.
Case 1 :
If your customer_id is an integer type and you have not put anything in default value then it will not allow you to insert a null into that field. For that, you need to set default value as NULL.
Case 2
If your customer_id is an autoincrement id of customer table then you can't set null into it during a SQL statement.

Mysql, How to read auto increment value in other fields of the same inserting row?

Hello I need to have the transaction id in the comment field of my transaction
mysql_query("INSERT INTO `transactiontb` (`tid`, `amount`, `comment`) VALUES (NULL,'$amount', CONCAT('Transaction # ',`tid`)')");
How can i do this?
Get off of mysql_* functions. Look at MySQLi or PDO.
Don't store the tid twice. Why not concat when you select it instead of storing it that way? This is not the best way.
For reference though, try LAST_INSERT_ID()+1):
INSERT INTO `transactiontb` (`tid`, `amount`, `comment`)
VALUES (NULL, '$amount', CONCAT_WS('Transaction # ', LAST_INSERT_ID()+1))
LAST_INSERT_ID() will give the ID of the previous INSERT not the one from the current INSERT so you must add 1.
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
The ID that was generated is maintained in the server on a
per-connection basis. This means that the value returned by the
function to a given client is the first AUTO_INCREMENT value generated
for most recent statement affecting an AUTO_INCREMENT column by that
client. This value cannot be affected by other clients, even if they
generate AUTO_INCREMENT values of their own. This behavior ensures
that each client can retrieve its own ID without concern for the
activity of other clients, and without the need for locks or
transactions.
Use the LAST_INSERT_ID() function.
LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value
representing the first automatically generated value that was set for
an AUTO_INCREMENT column by the most recently executed INSERT
statement to affect such a column.
Source: MySQL Documentation
Example:
"INSERT INTO transactiontb(tid, amount, comment) VALUES (NULL,'" . $amount . "', CONCAT_WS('#','Transaction',LAST_INSERT_ID(id+1)))"
Just saw you were also forgetting to put the separator for you CONCAT_WS function, so i fixed it in the example query.

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.

Check with sql if two tables are unique PHP

How can I check in MYSQL PHP if two columns are unique then not insert again, else if just one column is unique then insert, is that even possible to do in php?
EDIT:
Lets say I have a table like this,
userId | codeId
And I I send a query like this,
$query = $pdo->prepare('insert into table (userId, codeId) values (?,?)');
So now I want to check if userId and codeId are added already once do not insert again, and if just one is added, then do insert the entire query,
I hope its more understanding.
Set up a unique key for those columns, then the mysql query will FAIL when you try to insert.
Use REPLACE INTO instead of INSERT INTO ... ?
Do something like the code below (where TEXT_ID and TEXT_CATEGORY, are keys of table):
INSERT INTO
table_texts
SET
text_id = 174,
text_category = "pam_texto"
ON DUPLICATE KEY UPDATE
text_id = 174,
text_category = "pam_texto";
The above code tries to insert, but if the keys are duplicated performs an update on the line.

If mysql db table does not contain row with specific ID , add data to the table

Hi i'm new to php and mysql.
I'm wondering how can i use PHP to check if a table in my mysql database contains a ROW which have the specific ID and if not add the data to the table .
For example,
Table structure:(Table name : record)
ID , DATA
i have ID=123 and DATA=hello stored in a variable in the php code , how can i use php sql query to find out whether the data exist by checking using its ID in the table , if not , INSERT the ID and DATA into the table.
I hope you understand.
p/s i have connected the php script to the database
Make the ID UNIQUE:
CREATE TABLE my_table( ID INT UNSIGNED UNIQUE...
then use INSERT IGNORE:
INSERT IGNORE INTO my_table( ID, DATA ) VALUES( some_id, some_data )
IF NOT EXISTS(SELECT 1 FROM structure WHERE ID = <yourid>)
INSERT INTO structure (ID, DATA) VALUES(<yourid>, <yourdata>)
Just replace INSERT with REPLACE.
http://dev.mysql.com/doc/refman/5.5/en/replace.html
Another option:
INSERT INTO record(id, `data`) SELECT 123, 'hello'
FROM new_table WHERE NOT EXISTS (SELECT id from record where id = 123 );
If your ID is unique key, then you can directly try to insert the row. If that ID is already in the table, the database would not let you insert it and will return error. Else you have to first run a SELECT statement to see if this ID exists in your table and if not insert it.
Also this thread will help you a lot I think How to 'insert if not exists' in MySQL?

Categories