I know there are various offered solutions for this topic posted on this site, and I checked (and used) some of those solutions. Nevertheless, I can't figure out why my code below does not work, probably because I'm a starter with respect to php and sql programming ;-(
The code is supposed to add a record with 3 fields (FirstName, LastName, Age) in a table (persons), but only if the record does not already exist. Therefore a check on existing FirstName and Lastname fields is performed. But in case of existing record the condition of the if statement still seems to be true and a copy of the existing record is still inserted into the database. What do I miss?
Thanks in advance for the help.
//check whether item does not exist in database
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='$data[1]' AND LastName='$data[2]'";
$result = mysql_query($query);
if($result && mysql_num_rows($result) > 0)
{
echo " <br> record exist";
}
else
{
$theage = (int)$data[3]; //! for conversion of integer values
$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$data[1]','$data[2]','$theage')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
You have to use {} around array values in query
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='{$data[1]}' AND LastName='{$data[2]}'";
Also your INSERT query runs on mysqli and SELECT query runs on mysql. You have to use only 1 not both and use below code with mysqli.
$result = mysqli_query($con,$query);
if($result && mysqli_num_rows($result) > 0)
{
echo " <br> record exist";
}
May be this query will help you:
INSERT INTO persons (FirstName, LastName, Age)
SELECT * FROM (SELECT FirstName,LastName) AS tmp
WHERE NOT EXISTS (
SELECT FirstName, LastName FROM persons WHERE WHERE FirstName='$data[1]' AND LastName='$data[2]'
) LIMIT 1;
Check your connection
In first query you have used
mysql_query
then in second case at the time of insert you use
mysqli_query
From the database perspective, modify your Person table design by setting a UNIQUE KEY for the necessary fields i.e :
CREATE TABLE `Persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_FirstName_LastName` (`FirstName`,`LastName`) USING BTREE
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Do a normal insert, handle the duplicate error
[Err] 1062 - Duplicate entry 'jk-kenneth' for key 'unique_FirstName_LastName'
Related
I want to use one form to insert into two different Microsoft sql tables. I tryed to use 2 inserts, but didnt work.
if (isset($_GET['submit'])) {
$sth = $connection->prepare("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
echo "INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter',$Datum,'$Verbleib','$DUTNr')";
$sth->execute();
if($sth)
{
echo "";
}
else
{
echo sqlsrv_errors();
}
$MID = $connection->prepare("MAX(MID) as MID FROM DB.dbo.Fehler WHERE DB.dbo.Fehler.TestaufstellungID = '". $TestaufstellungID . "'");
$MID->execute();
$sth2 = $connection->prepare("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES ($MID, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$sth2->execute();
To understand MID is the Primary key of table Fehler and ist the foreign key in the second table Fehlerinfo
Thats why i have the select work around to get the last MID and want to save it in a variable $MID to insert it into the second table.
Is there a smarter solution possible?
As I mentioned in the comments, generally the better way is to do the insert in one batch. This is very over simplified, however, should put you in the right direction. Normally you would likely be passing the values for the Foreign Table in a Table Value Parameter (due to the Many to One relationship) and would encapsulate the entire thing in a TRY...CATCH and possibly a stored procedure.
I can't write this in PHP, as my knowledge of it is rudimentary, but this should get you on the right path to understanding:
USE Sandbox;
--Couple of sample tables
CREATE TABLE dbo.PrimaryTable (SomeID int IDENTITY(1,1),
SomeString varchar(10),
CONSTRAINT PK_PTID PRIMARY KEY NONCLUSTERED (SomeID));
CREATE TABLE dbo.ForeignTable (AnotherID int IDENTITY(1,1),
ForeignID int,
AnotherString varchar(10),
CONSTRAINT PK_FTID PRIMARY KEY NONCLUSTERED(AnotherID),
CONSTRAINT FK_FTPT FOREIGN KEY (ForeignID)
REFERENCES dbo.PrimaryTable(SomeID));
GO
--single batch example
--Declare input parameters and give some values
--These would be the values coming from your application
DECLARE #SomeString varchar(10) = 'abc',
#AnotherString varchar(10) = 'def';
--Create a temp table or variable for the output of the ID
DECLARE #ID table (ID int);
--Insert the data and get the ID at the same time:
INSERT INTO dbo.PrimaryTable (SomeString)
OUTPUT inserted.SomeID
INTO #ID
SELECT #SomeString;
--#ID now has the inserted ID(s)
--Use it to insert into the other table
INSERT INTO dbo.ForeignTable (ForeignID,AnotherString)
SELECT ID,
#AnotherString
FROM #ID;
GO
--Check the data:
SELECT *
FROM dbo.PrimaryTable PT
JOIN dbo.ForeignTable FT ON PT.SomeID = FT.ForeignID;
GO
--Clean up
DROP TABLE dbo.ForeignTable;
DROP TABLE dbo.PrimaryTable;
As i mentioned the answer how it works for me fine atm.
if (isset($_GET['submit'])) {
$failInsert = ("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
$failInsert .= ("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES (NULL, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$failInsert .= ("UPDATE DB.dbo.Fehlerinfo SET DB.dbo.Fehlerinfo.MID = i.MID FROM (SELECT MAX(MID)as MID FROM DB.dbo.Fehler) i WHERE DB.dbo.Fehlerinfo.TestID = ( SELECT MAX(TestID) as TestID FROM DB.dbo.Fehlerinfo)");
$sth = $connection->prepare($failInsert);
$sth->execute();
}
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;
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
i have this code that work well.
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses";
mysql_query($sql);
i put this into this page :
> http://localhost/msigilearnv2/tools/calender/copy_database.php
when first runs the page it will copy table from at_courses to phpc_events..
when second runs.. how i can prevent duplication data? because it keep add same data. i put ignore but still not works
I am sharing you one of the alternative. Lets say you have a record in the database and cid value is '1'.
First step check the value if it is already exists in the database.
$sql = "SELECT cid FROM phpc_events";
$returned = mysql_query($sql);
if(mysql_num_rows($returned) > 0){
while( $row = mysql_fetch_array($returned) ){
$PhpcArray [] = $row; //stores result returned in array to ensure less resource used
}
}
$sqlC = "SELECT anotherId FROM at_courses";
$returnedC = mysql_query($sqlC);
if(mysql_num_rows($returnedC) > 0){
while( $rowC = mysql_fetch_array($returnedC) ){
if( in_array( $rowC['anotherId'], $PhpcArray ) ){
// do nothing as id is already exists in phpc_events
}
else{
// do insertion because id in at_courses is not exist yet in phpc_events
}
}
}
Hope this helps.
Another alternative.
By the way you can also try this query if it matches your column as I don't know how your table structure looks like
SELECT cid
FROM at_courses
WHERE cid NOT IN (
SELECT cid FROM phpc_events
)
This query will return the cid in the at_courses which is not yet occur in phpc_events. Then do the insertion for those cid returned from at_courses table.
Thank you.
My MySQL isn't great, but you will need to do something the like:
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses"
left join phpc_event on phpc_events.cid = at_courses.cid //(and others you want matched for dups
where phpc_events.cid is null
;
If you have a primary key in your tables, you can replace INSERT with REPLACE. This will insert new records or replace them if the primary key already exists.
alter the table by adding UNIQUE constraint
ALTER TABLE phpc_events ADD CONSTRAINT your_field UNIQUE (cid, owner, subject, description, ctime)
So I've got this query:
mysql_query(
"INSERT INTO wall_post (post,username,userip,date_created)
VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."'
)"
);
and I also tried to make the query this way:
mysql_query(
"INSERT INTO wall_post (post,username,userip,date_created)
VALUES(
'".checkValues($_REQUEST['value'])."',
$_SESSION['user'],
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."'
)"
);
I don't see any error message from the database when the insert fails.
It won't insert the username into the database but when I echo $_SESSION['user'] it would still show me its content, please I would appreciate some help.
The table structure is:
CREATE TABLE wall_post (
p_id int(11) NOT NULL auto_increment,
username varchar(50) NOT NULL,
post varchar(255) NOT NULL,
image varchar(50) NOT NULL,
date_created int(11) NOT NULL,
userip varchar(200) NOT NULL, PRIMARY KEY (p_id)
)
The value which contains $_SESSION['user'] is theil, it doesn't have any special character, but if I replace $_SESSION['user'] with a string like $user = "test"; it will insert the value "test" into the database
mysql_query for insert statements either returns True on success or False on error. You have to check the return value if it was successful, and if it wasn't successful get the error via mysql_error:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
It should be easy to fix from there.
The image column is set to NOT NULL, but you are not inserting anything into it. I suspect removing the NOT NULL clause, or setting a default value for the column might fix your problem.
Additional tip. use MYSQLS NOW() for the date. Just let the database handle that bit :)
just check what the value is and make sure there are no special characters in there.
You can also try "'.mysql_real_escape_string($_SESSION['user']).'"
the problem might be special characters.
From all the comments try this
$name = isset($_REQUEST['user']) ? $_REQUEST['user'] : '';
mysql_query('INSERT INTO wall_post (post,username,userip,date_created) VALUES("'..checkValues($_REQUEST['value']).'",
"'.$name.'","'$ipAddress'","'.$timestamp.'")');
From one of your comments above, I learnt that if you echo your query, it shows as
INSERT INTO wall_post (post,username,userip,date_created)
VALUES('','theil','127.0.0.1','1309975742')
Did you do this echo just before the statement where you run the query? If not, I'd request you to please do the echo just before the call, like this:
echo "INSERT INTO wall_post (post,username,userip,date_created) VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."')";
mysql_query("INSERT INTO wall_post (post,username,userip,date_created) VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."')"
);
Your query seems to be absolute fine and should run fine. The only reason why username might not be saving into the database is that `$_SESSION['user'] is empty or does not exist.
Did you try running this echoed query - INSERT INTO wall_post (post, username, userip, date_created) VALUES('', 'theil', '127.0.0.1', '1309975742') - directly into MySQL, either on the prompt or any other client that you might be using?