Auto increment id - php

This is query where i want to insert new data to database. Before this id is auto by using old system and now i make a new form by php. This is my query and now i want make auto increment id.How to make a auto increment id.Please Help me if anyone know.
$sql="INSERT INTO $tbl_name(id, name, icno, email, applyIntake_id, modeOfStudy_id,
choice1_id, dob, nationalityType, gender_id, race_id, highestEducation_id,
address1, address2, postcode, city, state_id, permanent_address1,
permanent_address2, permanent_postcode, permanent_city, permanent_state,
telephoneNo, mobileNo)
VALUES('$name', '$icno', '$email', '$id', '$applyIntake_id', '$modeOfStudy_id',
'$choice1_id', '$dob', '$nationalityType', '$gender_id', '$race_id',
'$highestEducation_id', '$address1', '$address2', '$postcode', '$city',
'$state_id', '$permanent_address1', '$permanent_address2',
'$permanent_postcode', '$permanent_city', '$permanent_state',
'$telephoneNo', '$mobileNo')";
$result=mysql_query($sql);

Try this for MYSQL DB..
ALTER TABLE
`TABLE_SCHEMA`.`TABLE_NAME`
CHANGE COLUMN
`ID` `ID` INT(6) NOT NULL
AUTO_INCREMENT;

Ok, one thing first: you should escape your parameters! See here.
To solve your problem: you can define a field in the database as auto_increment, what will automatically increment the id if left empty.

Amir you have 3 errors in above insert.
The columns count match but you try to insert into #tbl_name(email) value of $id
Please set the id field as autoincrement the answer is in above posts.
I think when preparing PHP $sql variable you have to use "." as string operator to get proper SQL INSERT statement with data from your variables - currently the below INSERT will insert instead of your name variable $name as string into DB.
Exmaple :
$name = 'Tom';
$email = 'tom#o2.pl'
$sql = "insert into table(name,email) VALUES (".$name.",".$email.");";
Then use following insert but apply the example of string join above - it should work:
$sql="INSERT INTO $tbl_name(name, icno, email, applyIntake_id, modeOfStudy_id,
choice1_id, dob, nationalityType, gender_id, race_id, highestEducation_id,
address1, address2, postcode, city, state_id, permanent_address1,
permanent_address2, permanent_postcode, permanent_city, permanent_state,
telephoneNo, mobileNo)
VALUES('$name', '$icno', '$email', '$applyIntake_id', '$modeOfStudy_id',
'$choice1_id', '$dob', '$nationalityType', '$gender_id', '$race_id',
'$highestEducation_id', '$address1', '$address2', '$postcode', '$city',
'$state_id', '$permanent_address1', '$permanent_address2',
'$permanent_postcode', '$permanent_city', '$permanent_state',
'$telephoneNo', '$mobileNo')";
$result=mysql_query($sql);

ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.

Related

How to replace some values if a user already exists?

I don't know how to replace some data if a "user" already exists.
I've tried ON DUPLICATE KEY UPDATE but I came to realize that this will probably not work. Because the only value that isn't updated is 'user' in my code but the other 3 values are constantly updated every 5 minutes.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES ('$Name'), world = VALUES ('$World'), status = VALUES ('$status')
The idea is if, for example, user "bob" already exists update his other 3 values bot, world, status, instead of creating a new line and so on.
Edit: this is how I have it setup in Mysql
The argument to VALUES() should be the name of a column, not a string. You put the name of the column that you would have inserted into.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES (bot), world = VALUES (world), status = VALUES (status)

cannot insert data into table in mysql using php

here, i try to insert some data from my form, but there is always not inserted and i dont know where is the error, hope anyone tell me :)
my insert code
$sql="INSERT INTO $tbl_name (buyername, buyerjob, buyercompany, buyeraddress, buyercity, buyerpost, buyerphone, buyerfax, buyeremail, buyerweb, buyernob, buyertoo, buyerhonor)
`VALUES ('$name', '$job', '$company', '$address', '$city', '$post', '$phone', '$fax', '$email', '$web', '$nob', '$too', '$bhonor')";
is there any error? hope anyone help
Error Message
#1452 - Cannot add or update a child row: a foreign key constraint fails
(reg_db.buyer_db, CONSTRAINT buyer_db_ibfk_1 FOREIGN KEY (spouse_id) REFERENCES
spouse_db (spouse_id))
You don't set a value of spouse_id field,
but error message says that it is mandatory and must be set to a value present in spouse_db table.

Error in executing insertion query

Isn't this query correct?
$insert = INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10');
I got following error, please help I am a beginner.
Parse error: syntax error, unexpected 'INTO' (T_STRING) in
C:\xampp\htdocs\google.php on line 9
$insert = "INSERT INTO `geninfo` (`S.N`, `Name`, `Address`, `DOB`) VALUES ('Suresh','Ratnanagar','Missing address here','1989/04/10');";
Note that I have also corrected your MySQL query. S.N refers to the column named N on the table named S, which I'm pretty certain is not what you wanted.
Also I just realised you have four columns, but only three values. Fixed that too.
You have no quotes, it should be like this:
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10')";
upd
It seems you are storing date of birth as a string, not as a timestamp (or similar) which is not a good idea
You need to give a (NULL or '') for the S.N field and quotes should be given before and after each and every value.
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES
('', 'Suresh','Ratnanagar','1989/04/10')";
Moreover the field name S.N could create problems. Let me know if this works.
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10')";

Writing to a data table with just foreign keys

I have a PostGreSQL database with the following data model:
CREATE TABLE staff (s_id serial UNIQUE, name, username, password, email)
CREATE TABLE institution (i_id serial UNIQUE, name);
CREATE TABLE isStaffOf (i_id, s_id); //foreign key references
When a user submits the form I have a PHP script which writes the information to first two data tables and that automatically generates the s_id and i_id values. Great!
I've tried out a few PHP modifications to get the system writing both the s_id and i_id into the isStaffOf relation so it can enforce the explicit 1..1 relationship required for my project but on submit it says I have an insufficient data type. See below for the PHP code.
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$institution = $_POST["institution"];
$conn = pg_connect("host=***** port=**** dbname=****** user=**** password=******");
$staffWrite = pg_query("INSERT INTO staff(name, username, password, email) VALUES ('$name', '$username', '$password', '$email')");
$instiWrite = pg_query("INSERT INTO institution(name) VALUES ('$institution')");
$instiFK=pg_query("SELECT i_id FROM institution WHERE name='$institution'");
$staffFK=pg_query("SELECT s_id FROM staff WHERE name='$username'");
$sql=("INSERT INTO isstaffof(i_id, s_id) VALUES ('$instiFK', '$staffFK')");
$result = pg_query($sql);
That is the script I have at the moment but its not working. Any ideas on how to fix this so that when a user submits all the data tables will be filled and the referential integrity enforced? I'm almost there and still trying things out but to no avail.
The error message:
ERROR: invalid input syntax for integer: "Resource id #4" LINE 1: INSERT INTO isstaffof(i_id, s_id) VALUES ('Resource id #4', ...
Please let me know if you need more explanation but I'm sure its clear what I want to achieve and I'm convinced I can do it without so many pg_query calls.
As of PostgreSQL version 9.1, you can use a single query to INSERT in all 3 tables, a writable common table expression:
WITH
step_1 AS(
INSERT INTO staff (name) VALUES('Frank') RETURNING s_id
),
step_2 AS (
INSERT INTO institution (name) VALUES('PostgreSQL') RETURNING i_id
)
INSERT INTO isStaffOf (i_id, s_id) SELECT i_id,s_id FROM step_1, step_2;
Simple, fast and reliable.
You could do some other tricks as well, when some records already exists and just want to select the primary key value.
WHEN creating the isstaffof table, you at least have to specify the datatypes, and you can specify they are foreign keys.
CREATE TABLE isstaffof
(i_id BIGINT REFERENCES institution(i_id)
, s_id BIGINT REFERENCES staff(s_id)
);
NOTE: avoid using MixedCase for identifiers. It might cause terrible problems, if you ever have to port to a different DBMS platform.
UPDATE: Just put it in a plain INSERT INTO ... SELECT ... FROM ... statement.
CREATE TABLE staff (s_id serial UNIQUE, sname varchar);
CREATE TABLE institution (i_id serial UNIQUE, iname varchar);
CREATE TABLE isstaffof
(i_id BIGINT REFERENCES institution(i_id)
, s_id BIGINT REFERENCES staff(s_id)
);
INSERT INTO isstaffof(i_id,s_id)
SELECT i.i_id,s.s_id
FROM staff s, institution i
WHERE i.iname='$institution'
AND s.sname = '$staff'
;
Now, you can wrap that into your front-end code.
You'll have to fetch the result with pg_fetch_assoc or something similar. The way you're using it now you're passing the whole pg_query resource as an integer - obviously php can't convert that to a valid integer.
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$institution = $_POST["institution"];
$conn = pg_connect("host=***** port=**** dbname=****** user=**** password=******");
$staffWrite = pg_query("INSERT INTO staff(name, username, password, email) VALUES ('$name', '$username', '$password', '$email')");
$instiWrite = pg_query("INSERT INTO institution(name) VALUES ('$institution')");
$instiFK=pg_query("SELECT i_id FROM institution WHERE name='$institution'");
$rowInsti = pg_fetch_assoc($instiFK);
$staffFK = pg_query("SELECT s_id FROM staff WHERE name='$username'");
$rowStaff = pg_fetch_assoc($staffFK);
$result = pg_query("INSERT INTO isstaffof(i_id, s_id) VALUES (".$rowInsti['i_id'].", ".$rowStaff['s_id'].")");
As an alternative you could probably use pg_last_oid directly after every insert to get the id. (Even more beautiful would the RETURNING-solution be. Just read the comments on the php.net page)

MySQL: Insert if this ip dont have any records

I use:
INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
'{$_SERVER['REMOTE_ADDR']}');";
I would like to add an if condition in the IF statement so that.
IF SELECT ip from rating
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name
then update ELSE INSERT new row
is it doable or I better code it in php ?
thank you very much
P.s: I know how to do it with php, I want to learn it with MySQL.
Also i require that all 3 name,section,ip matchs not only ip
Assuming you have a unique constraint (UNIQUE index or PRIMARY KEY) on ip, section and name, you can use this syntax:
INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section', '{$_SERVER['REMOTE_ADDR']}')
ON DUPLICATE KEY UPDATE user = VALUES(user), rating = VALUES(rating);
To expand on Eric's excellent answer.
To add a unique constraint on each of the columns ip, name, section run the following code on the database
ALTER TABLE `test`.`rating`
ADD UNIQUE INDEX `name`(`name`),
ADD UNIQUE INDEX `section`(`section`),
ADD UNIQUE INDEX `ip`(`ip`);
To run a unique constraint on the combination of columns ip+name+section do:
ALTER TABLE `test`.`rating`
ADD UNIQUE INDEX `name_section_ip`(`name`, `section`, `ip`);
The last thing is probably what you want.
One last thing
I'm not 100% sure, but this usage of {$_SERVER['REMOTE_ADDR']} in the query does not look SQL-injection safe.
Consider changing it into:
$remote_adr = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$session = mysql_real_escape_string($_SESSION['user']);
$query = "INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '$session', '$rate', '$section','$remote_adr')";
Finally putting a ";" in a mysql_query() like so mysql_query("select * from x;"); does not work mysql_query() will only ever execute one query and will reject your ;.

Categories