Insert into two tables from a single form. The first insert go in fine the second generates this error Duplicate entry '0' for key 1 any idea what is happening?
$connection=mysql_connect ("localhost", "foo", "bar") or die ("I cannot connect to the database.");
$db=mysql_select_db ("database", $connection) or die (mysql_error());
$query = "INSERT INTO worklog (id, newtime, datetime, clientname, clientcode, startmo, startday, startyr, endmo, endday, endyr, duemo, dueday, dueyr, market, job, allTypes, spec, status, designer, dsgnemail, adrep, ademail, frame1, frame2, frame3, rush) VALUES ('$id', $newtime, now(), '$clientname', '$clientcode', '$startmo', '$startday', '$startyr', '$endmo', '$endday', '$endyr', '$duemo', '$dueday', '$dueyr', '$market', '$job', '$allTypes', '$spec', '$status', '$designer', '$dsgnemail', '$adrep', '$ademail', '$frame1', '$frame2', '$frame3', '$rush')";
$sql_result = mysql_query($query, $connection) or die (mysql_error());
$worklog_id=mysql_insert_id($connection);
$connection2=mysql_connect ("localhost", "foo", "bar") or die ("I cannot connect to the database.");
$db2=mysql_select_db ("database", $connection2) or die (mysql_error());
$query2 = "INSERT INTO worklognotes (worklog_id, spec) VALUES ('$worklog_id', '$spec')";
$sql_result = mysql_query($query2, $connection2) or die (mysql_error());
I thin the culprit is the line:
$worklog_id=mysql_insert_id($connection);
according to the PHP documentation:
"The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established"
So if the id in worklog is not AUTO_INCREMENT it will always return 0 ... your second attempt at running the code will cause:
Duplicate entry '0' for key 1
Two ways to fix this:
id for worklog should be AUTO_INCREMENT ... this way mysql_insert_id will return ther ID generated by the database and you can use it as a working id for the next query
just use $id instead of $worklog_id
normally with and table ID column you set it to auto-increment and never explicitly insert it. The database management system will take care of inserting that column. The error means that you are inserting a row that has that ID already, meaning the column has a UNIQUE constraint.
Related
So I have this short script. Its not giving out any error but it will not save into the DB. After I run the script I check the DB and nothing is there.
The db only has two items. (id and fid) ID is set at INT 11 auto and fid is set at VARCHAR 64. Also, I am connecting to my DB just fine.
<?php
$con = mysqli_connect('####', '####', '####', '#####');
if (mysqli_connect_errno()) {
echo 'Failed to Connect to MySQL' . mysqli_connect_errno();
}
if (isset($_POST['submit'])) {
$fid = $_POST['fid'];
$query = mysqli_query($con, "SELECT * FROM fid where fid = '$fid'");
$row = mysqli_num_rows($query);
if ($row == 1) {
echo 'This Federal Tax ID is already in use.';
} else {
mysqli_query($con, "INSERT INTO `fid` (id, fid) VALUES ('', '$fid')");
}
}
?>
Based on your comment:
It's supposed to be an empty value so the ID auto increments everytime.
That's not how auto-increment works. Your code is explicitly telling the record to not have a value:
"INSERT INTO `fid` (id, fid) VALUES ('', '$fid')"
If the id column is required, this will expectedly fail. (It may also be failing based on the type. You're trying to insert a string, but an auto-increment column would be numeric...)
An auto-increment column doesn't need to be supplied an empty value. Just omit it entirely:
"INSERT INTO `fid` (fid) VALUES ('$fid')"
Additionally, this code is wide open to SQL injection. You're going to want to read up on that. In short, you should use prepared statements which bind to user-input values. Don't concatenate those user-input values directly into your code, that allows the user to inject their own code.
If you want to use AUTO you need to either NOT specify the value at all or else specify a 0 (or NULL if defined as NOT NULL):
Either
INSERT INTO fid (fid) VALUES ('$fid')
or
INSERT INTO fid (id, fid) VALUES (0, '$fid')
or (if id is defined as NOT NULL)
INSERT INTO fid (id, fid) VALUES (NULL, '$fid')
SOURCE: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
For two hours now, I'm trying to insert a value into a table. I don't get any error and I can't find out the problem!
The value that I'm trying to insert:
$query = "INSERT INTO banlist (banid, active, ip, by, date, reason) VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')";
mysql_query($query);
An example value that works perfectly:
$query = "INSERT INTO accounts (username, password, email, regdate) VALUES ('test', 'test', 'test#test.test', 't-t-t t:t:t')";
mysql_query($query);
I can't find the problem! Am I missing anything? Both tables exist.
The issue is that the name you've chose for a field "by" is a reserved word. You'll have to update it to a word that's not on this list.
Also, in future you can easily see what's wrong by checking if mysql_query() returned false, and then calling mysql_error() for an error message.
Try this:
CREATE TABLE ban (
banid int auto_increment primary key,
active int,
ip varchar (20),
`by` varchar (20),
`date` varchar(8),
reason varchar(20)
);
INSERT INTO ban (active, ip, `by`, `date`, reason)
VALUES
(1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
;
SELECT * FROM ban;
http://www.sqlfiddle.com/#!2/1959f/1
Some remarks:
Like several others (e.g. #wintercounter, #user1909426 ) have pointed out you are using restricted words in MySQL. If you do use a restricted word then use `` (back ticks) or just use them on every column.
I think that using a null in your first part of you insert gives a problem. This column is probably an integer column with auto_increment. See #wintercounter answer.
Fortunately date is not a restricted name. B.T.W. you could use use a date value instead of you varchar value now.
With regard to the comments from #tadman using mysql instead of mysqli or PDO is not recommended. The mysql library is depreciated from version PHP 5.5 onwards, see the php manual. You will also need to include error handling.
For completeness sake, this is the php code when using MySQLi:
$link = mysqli_connect($hostname, $username, $password, $database);
if (!$link){
echo('Unable to connect to database');
}
else{
mysqli_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test'))", $link);
}
mysqli_close($link);
For mysql version:
$hostname = "hostname";
$username = "username";
$username = "password";
$database = "database";
$link = mysql_connect($hostname, $username, $password);
mysql_database ($database)
if (!$link){
echo('Unable to connect to database');
}
else{
mysql_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test')");
}
mysql_close($link);
use mysql error statement in each variable for know which line your mistake occured.
The query probably doesn't display an error because error_reporting is turned of in your php.ini:
try setting error_reporting to E_ALL.
Also the query might not work because you are sending "NULL" as value for banid which is probably a either a primary key or a foreign key / index that doesn't allow a NULL value.
Try this:
INSERT INTO `banlist` (`banid`, `active`, `ip`, `by`, `date`, `reason`) VALUES ('', 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
As stated, 'by' is reserved keyword, but you can help to MySQL in the parse so it'll know if it's a field name or a command.
EDIT:
I've changed NULL to ''. I'm not sure in this, never tried, but if it's an AI field, maybe you can't use NULL there, just use an empty content as a placeholder for ID field.
Just try this:
INSERT INTO banlist VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
Here is an easy one, but can't figure out why is not working. Need another set of eyes.
3 queries. 1 insert, 1 select, then 1 insert again. My select query is supposed to grab a value from the data recently inserted, and then store that value in a variable, then run the second insert for another table. Well, everything works, except the select. I even tryied to add a mysql_query("COMMIT",$conn) and still nothing.
Any help is very appreciated.
Thanks!!!
$customerQ = "INSERT INTO
customerData(fname, mname, lname, email, homePhone, cellphone, address,
city, county, state, zip, gascompany, eleccompany, addedBy)
VALUES('$fname', '$mname', '$lname', '$emailCustomer', '$hphone', '$cellphone',
'$address', '$city', '$county', '$state', '$zip', '$gas', '$electric',
'$userName'
) ";
//General WO# calculation
$calcWO = "SELECT
auditRequest.workOrderNum
FROM
auditRequest
ORDER BY
auditRequest.workOrderNum DESC
LIMIT 1
";
//General Customer number calculation. For the Work Order Insert
$calc = "SELECT
customerData.custnumber
FROM
customerData
WHERE
fname = '$fname' and
mname = '$mname' and
lname = '$lname'
ORDER BY
customerData.custnumber DESC
LIMIT 1
";
//Customer Information Insert (from Insert Query)
$resultCustQ = mysql_query($customerQ, $connection);
mysql_query("COMMIT", $connection); //make sure to commit to be able to query new records
// Test the query
if(!$resultCustQ) die ("error 1". mysql_error());
//Customer Information Insert (from Insert Query)
$resultCustQ = mysql_query($customerQ, $connection);
mysql_query("COMMIT", $connection); //make sure to commit to be able to query new records
// Test the query
if(!$resultCustQ) die ("error 1". mysql_error());
//Calculate new customer number
$calc_result = mysql_query($calc, $connection);
// Test the query
if(!$calc_result) die ("error 1". mysql_error());
$row=mysql_fetch_array($calc_result);
$custnum = $row['custnumber']; // This is the new Customer.
//Work Order Information (run SQL Insert)
$resultWOQ = mysql_query($workOrderQ, $connection);
// Test the query
if(!$resultWOQ) die ("error 1". mysql_error());
I would avoid the crutch of INSERT followed by SELECT to find the inserted record altogether and use MySQL's ability to return the ID of the most recently inserted row (provided your table as an AUTO INCREMENT primary key) via PHP's mysql_insert_id, also available through PDO via lastInsertId.
Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.