Insert new row in a table and auto id number - php

I want to insert a new row in my table. I want the id to be generated right automatically and not asked from the user. The user only provides title and text. I wrote this code in PHP:
<?php
$hostname = "localhost";
$database = "mydb";
$username = "myuser";
$password = "mypsw";
$link = mysql_connect( $hostname , $username , $password ) or
die("Attention! Problem with the connection : " . mysql_error());
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES ‘utf8’",$link);
mysql_select_db("mydb", $link);
$lastid=mysql_insert_id();
$lastid=$lastid+1;
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
if (!mysql_query($sql,$link))
{
die('Error: ' . mysql_error());
}
mysql_close($link);
header("Location: announcement.php");
?>
Sadly when I test it on my website, I get this error:
Error: Duplicate entry '0' for key 'PRIMARY'
Is mysql_insert_id() not working? What is wrong?

Don't do this. mysql will happily create an auto_increment column for you:
CREATE TABLE x (
id int not null primary key auto_increment
^^^^^^^^^^^^^^---add this to your PK field
);
INSERT INTO x (id) VALUES (null); // creates id = 1
INSERT INTO x (id) VALUES (null); // creates id = 2
mysql_insert_id() only returns the last id created by the CURRENT connection. You haven't inserted any data yet when you first run it, so you get back nothing.
Your version is incredibly vulnerable to race conditions. There is NO guarantee that the last ID you retrieve with mysql_insert_id() will not ALSO get retrieved by another copy of the script running in parallel, and get sniped out from under this copy of the script.

The primary key column on announcements should be auto_increment. When you do mysql_insert_id() it retrieves the id from the last query executed from that connection.
Because the INSERT is the query you are currently performing, it errors.
Try
INSERT INTO announcements
(date_field, title, text)
VALUES (CURDATE(),'$_POST[title]','$_POST[text]')
Just replace 'date_field', 'title', and 'text' with the applicable column names.
Alternatively the following should also work, as a NULL value in the AutoIncrement value should be acceptable
INSERT INTO announcements VALUES (NULL,CURDATE(),'$_POST[title]','$_POST[text]')
As mentioned in the other suggestion posted, you should make sure that the primary key field of the announcements table is set to be auto_increment.
Just for completion, you would use mysql_insert_id() when you want to use the id for the row you just inserted, i.e. if you then want to select the row you just inserted you could do
'SELECT * FROM announcements WHERE id = '.mysql_insert_id()

The problem is that you are asking for last insert id and you didn't inserted anything.
Convert your ID field in db to be autoincrement if its not.
Insert into database your announcment
Then ask for id using mysql_insert_id to get it.
But I see that you are not using it only when inserting then you don't need that functionality anyhow. Just insert without ID like this
"insert into announcements (InsertDate, Title, Text) VALUES (CURDATE(), '$_POST[title]', '$_POST[text]')";
and you should really be careful with your queries when using values from $_POST or $_GET or any other user typed value. There is possibility to execute SQLInjection through your form fields, so I suggest you to use mysql escape command or use parameters.
I hope this helps.

Assuming your table is set up properly, with the id field as AUTO_INCREMENT, you just need to perform an INSERT where you do not specify a value for id. That means you must specify the names of the columns you are inserting. So this line:
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
becomes this
$sql="INSERT INTO announcements (`date`,`title`,`text`) VALUES (CURDATE(),'$_POST[title]','$_POST[text]')";
I guessed what your column names might be. Obviously they need to match your table definition.
If you do this, then the mysql_insert_id() function will return the id of the row you just inserted. (That is, it gives you the value of the previous insert, not the next one.)

You probably want to add "auto increment" to the table when creating it.
This will add an id automatically when inserting something.
e.g.
CREATE TABLE announcements
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
some_date int(11),
title varchar(200),
text varchar(3000)
);
mysql_insert_id "Retrieves the ID generated for an AUTO_INCREMENT column by the previous query " - http://php.net/manual/en/function.mysql-insert-id.php

Related

Insert Multiple Value into table MySQL if not exists

I have a table with 3 columns (ID, username, full name), I want the ID to be AUTOINCREMENT. I want to insert into the table only if it does not already exist in the table.
This is my Code:
$fullName = $_POST['fullname'];
$username = $_POST['username'];
$dbhost = "localhost";
$dbname = "databasename";
$dbusername = "root";
$dbpassword = "";
$link = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","");
$statement = $link->prepare('INSERT INTO accounts (username, fullname)
VALUES (:username, :fname)');
$statement->execute([
'fname' => $fullName,
'username' => $usernameget,
]);
If your id is already autoncrement then you no need to mention in query.
You can simply write below query
insert into accounts (username,fullname) values( $username , $fullname )
you can do this with if else condition in PHP
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$chk = mysqli_query("select * FROM `accounts` where fullname='$fullname' and username='$username'");
$rs = mysqli_fetch_array($chk);
if($rs == "")
{
$ins = mysqli_query("INSERT INTO `accounts`(fullname,username) VALUES ('$fullname','$username'))";
}
else{
echo "Duplicate entry";
}
or you can do this by SQL Query also.
INSERT INTO accounts(username,fullname)
SELECT * from (SELECT '$username', '$fullname') AS tmp
WHERE NOT EXISTS
(SELECT username FROM accounts WHERE username='$username')
There's several things to fix here.
Don't specify column values if you don't need to, or don't care about the value. Only specify if necessary or relevant. In this case id should be omitted.
Always use placeholder values for your user data. Never put $_GET or $_POST data directly in a query.
To avoid duplication add a UNIQUE constraint on the table.
To fix that you do adjust your code:
// Enable exceptions, avoiding the need for manual error checking
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Try and keep the order of things like this consistent through your code
$username = $_POST['username'];
$fullname = $_POST['fullname'];
// Here using a short, common name for the database handle $db
$db = new mysqli("localhost","root","","database");
// Prepare your insert first as a query with no data, only placeholders
$db->prepare("insert into accounts (username,fullname) values(?,?)");
// Bind the data to the placeholders, here two string ("s") values.
$db->bind_param('ss', $username, $fullname);
// Execute the query
$db->execute();
To add the UNIQUE constraints use CREATE INDEX:
CREATE INDEX idx_accounts_username (username);
CREATE INDEX idx_accounts_full_name (full_name);
That has to be run in your MySQL shell, not PHP.
When a UNIQUE constraint is in place MySQL will not allow duplicate data. Note that NULL values don't count, and can be "duplicated". Set NOT NULL on your columns to force them to be completely unique.
As your id is autoincrement primary key, so you can create or update it with:
insert into accounts (username,fullname) values( $username , $fullname ) on duplicate key update username = '$username',fullname = '$fullname'
To get correct answers, a question must be asked with as much explanation as possible. you should atleast tell what have you done and then what are you getting.
As far as i have understood, to achieve your goal, the table structure must be changed and inserting query also.
Remember to accept the answer and click the upvote button if the answer satisfies you,else give more information in the question, so that members here, can give right answers.
If you understand table creating queries go to bottom of this answer or else do as follows:
if you use gui to create table,
1. click on create new table.
2. in the right pane give table name and column names as shown. (dont give space in 'full name' instead give 'full_name' or 'fullname')
3. scroll the winow to the right till you see A_I column as shown.
4. tick the first line (which we have used as id), 'add index' box will appear.
just click here go (at the bottom).
you will be redirected to table list as shown.
6. open (click) your table again.
7. click on structure.
now suppose you don't want duplicates in 'username' column, click this column and click on 'unique' as shown
if you don't want duplicate when both the columns' value together, click both the columns and then click 'unique' as shown
if you understand create table commands:here is the sql for above:
CREATE TABLE accounts (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(25) NOT NULL,
fullname varchar(55) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY username (username)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
with above table structure records will be autoincremented and duplicate names will not be added. (remember to handle duplicate entries error in you inserting querie withINSERT IGNORE INTOwith this your query will be:
$statement = $link->prepare('INSERT IGNORE INTO accounts (username, fullname)
VALUES (:username, :fname)');
or you can also useON DUPLICATE KEY)
First set your primary key (eg. id) if not set as auto increment
Second use multiple insertion value
INSERT IGNORE INTO accounts (username,fullname) VALUES ("p","k"),("c","s");
IGNORE keyword is use to duplicate
IF you want to see with PDO

MySQL one-to-may relationship

After looking around on stackoverflow, I'm still having a little trouble understanding the one-to-many relationship in mysql. I have a request coming in from the user (form submission) which will be stored in one table. This is a dynamic form that lets the user add extra fields therefore those will be stored in a separate table. So in short, in my db design, there will be one table for the users with PRIMARY KEY AUTO INCREMENT and there will be another table for the hostnames PER user (multiple fields -array) and using a foreign key that references to the primary key in the user table. Sorry if this is long but trying to make this a good question.
Example:
User Table: (ONE)
1. John Doe, blah, 11-12-15
2. Sally Po, blah, 11-14-15
3. John Doe, blah, 11-15-15
(these are three separate requests)
(numbers are primary key auto incr.)
Host Name Table: (MANY)
1. www.johndoe.com
1. www.johndoe2.com
1. www.johndoe3.com
2. www.sallypo.com
2. www.sallypo2.com
(these numbers (foreign key) should match the primary key for each request)
Code (Leaving out the actual queries + pretty sure I shouln't be using last_id):
$sql = "CREATE TABLE IF NOT EXISTS userTable (
id int AUTO_INCREMENT,
firstName VARCHAR(30) NOT NULL,
date DATE NOT NULL,
PRIMARY KEY (id)
)";
//query
$sql = "CREATE TABLE IF NOT EXISTS hostNamesTable (
id int NOT NULL,
hostName VARCHAR(90) NOT NULL,
FOREIGN KEY (id) REFERENCES userTable(id)
)";
//query
$sql = "INSERT INTO userTable (firstName, date)
VALUES ('$firstName', '$date')";
//query
$last_id = mysqli_insert_id();
for($i = 0; $i < sizeof($hostName); $i++){
$sql = "INSERT INTO hostNamesTable (id, hostName)
VALUES ('$last_id', '$hostName[$i]')";
//query
}
What am I doing wrong? (is this the right way to go about it?)
note: I was trying to get the last_id of the user Table so that I can use it in the hostName table as the foreign key
EDIT: I'm using MySQLi with php
EDIT 2:
After the changes, this is the error I am getting now: Cannot add or update a child row: a foreign key constraint fails (d9832482827984hb28397429.hostNamesTable, CONSTRAINT hostNamesTable_ibfk_1 FOREIGN KEY (id) REFERENCES userTable (id))Error: INSERT INTO hostNamesTable (id, hostName, ) VALUES ('', 'secondhost.net')
--Looks like the $last_id isn't even being recorded?
EDIT 3: Started working. Not sure what it was but I think it was because of some type.
why dont you just add an extra column in the hostNames table which is called "ref_user" and contains the ID of the user you are reffering to? So you can use unique IDs in both tables.
Make a query like:
SELECT * FROM hostNames WHERE ref_user = (SELECT id FROM userTable WHERE <uniqueColumn> = <uniqueIdentifierOfUser>);
But the included request must return only one line from users.
try adding mysqli $link as a parameter in your mysqli_insert_id
$last_id = mysqli_insert_id($link);
i presume you have this somewhere in your code
$link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mysql_db");
if this doesn't work, try using mysql LAST_INSERT_ID() function
$last_id = $mysqli->query("SELECT LAST_INSERT_ID() AS last_id")->fetch_object()->last_id;

Add a new record to database after checking value

I am inserting data into a database fine with the user entering a reference number eg 1234. Can I change my insert to not require the user to input the value and for the last value entered to be checked and then the reference number being inserted be incremented by one and then inserted with the other data. Bit of a new bee. Here is my current code
$Reference_No = $_POST['Reference_No'];
$Property_Name = $_POST['Property_Name'];
$Property_Area = $_POST['Property_Area'];
mysql_query("INSERT INTO properties (Reference_No, Property_Name, Property_Area)
VALUES ('$Reference_No', '$Property_Name', '$Property_Area')");
You need to make the Reference_No an AUTO_INCREMENT.
Step 1:Create table
CREATE TABLE properties (
Reference_No int AUTO_INCREMENT ,
Property_Name varchar(255),
Property_Area varchar(255),
PRIMARY_KEY (Reference_No)
)
Step 2 : Set the start for auto increment of primary key if you like
ALTER TABLE properties AUTO_INCREMENT=1234;
Step 3: Insert the data into the table
INSERT INTO properties (Property_Name, Property_Area)
VALUES ('$Property_Name', '$Property_Area')");
interogate the database for the Reference NO (where property name matches if you need it)
$reference_no_query = mysql_query("SELECT Reference_No FROM properties WHERE Property_Name = $Property_Name");
pull the Reference No out of the database
$Reference_no = mysql_fetch_array($reference_no_query)
display the Reference no
echo $Reference_no('Reference_no');
you can (and should) tie the data to a variable then echo the var like this:
$Reference_no_display = $Reference_no('Reference_no');
then display it directly from the variable anywere and as many times as you want in the page below the query:
echo $Reference_no_display;
This seems to do the trick for the final bit
printf("Last inserted record has id %d\n", mysql_insert_id());

Can only insert into mysql table once

I have an issue where I can only insert data into my table once. If i delete the row and insert a new one, it works but if I already have a row and try to insert another one, it doesn't work. No errors in the console or network.
I'm inserting with this:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = mysql_real_escape_string($_POST['name']);
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($sql, $con)
or die("Error: ".mysql_error());
mysql_close($con);
?>
I'm thinking it might have to do with how my table is set up, primary key and such. I have an id column which is the primary and I think it's auto-increment, can't tell.
Since you are not sure about whether the id field is auto-increment or not, you should alter your table like this,
ALTER TABLE `yourtable`
MODIFY COLUMN `id` int(11) NULL AUTO_INCREMENT FIRST;
the result FROM SHOW CREATE TABLE tableName would help.
I would guess you have a unique index on on of your fields and you are trying to insert a second record with the same value.
Also CHECK TABLE tablename could help identify the problem.
I had this... I had set my first column as 'unique' and my 'Insert' didn't involve that column.
As a result the 'Insert' added a value of zero into the 'Unique' column (I'd set that column to 'integer').
When I did another insert 'I THINK' that the 'Insert' wanted to add another zero in the 'Unique' column that I wasn't 'Inserting' into, so it tried to 'Insert' another zero, BUT because that column was 'unique' it wouldn't allow another zero and refused the 'Insert'.
I proved this by changing the first 'Inserts' entry into the 'Unique' column manually to another 'Integer' then the 'Insert; statement worked one more time.... repeat process above as described and my table allowed another 'Insert'.
Hope this makes sense and helps?.
I had a similar problem, however mine was where I was using the INT data type in my create table script for storing a 13-digit long number, and it only wanted to accept something 10-digits in size. Changing this to a VARCHAR(13) fixed the problem for me.

Modify rows to increment in MySQL

I have the following table: http://kimag.es/share/59074317.png
columns = [id cid comment]
I need a way to make the values of cid (comment id) increase by 1 for every row in the table.
row 1, cid=0
row 2, cid=1
row 3, cid=2
etc.
Now cid=id because of this php script:
<?php
$con = mysql_connect("localhost","MYUSER","MYPASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$id=0;
$totalrows=23207;
mysql_select_db("MYDB", $con);
while($id < $totalrows)
{
$sql = "UPDATE comments SET cid=$id WHERE id=$id";
mysql_query($sql,$con);
$id++;
}
mysql_close($con);
?>
Could someone provide an appropriate mysql query?
Note: I don't have any 'individual keys'... and I need the cid to correspond to a specific comment so I can delete it, modify it, etc. (yes, I should've thought of that before creating the table >_<).
Thanks!
Can't you just do:
ALTER TABLE comments ADD cid INT AUTO_INCREMENT PRIMARY KEY;
You'll need to drop the old cid column first.
If cid is primary key of your table then you can specify AUTO_INCREMENT attribute to it. Which will automatically assign unique values to all new rows inserted:
-- when use NULL as value for id mysql automatically set next unique number
INSERT INTO table (cid, id, comment) VALUES (NULL, ?, ?);
And you can alter existing data too:
ALTER TABLE table CHANGE cid cid INT NOT NULL AUTO_INCREMENT PRIMARY KEY;

Categories