MYSQL Duplicate rows - php

I am trying to insert values into a table in MYSQL, the table has a column which should be unique,so that column always will have different values.
I tried putting UNIQUE for the coloumn but it did not work,
Also tried putting that column as PRIMARY KEY and insert IGNORE INTO command it did not work (http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm)
My intention is to put phonenumber column unique so every value in this column is different. if the newly inserting value is not unique it should skip wihout giving error.
My code to Create table:
public function create_member_table($table)
{
$this->sql ="CREATE TABLE IF NOT EXISTS $table ( id BIGINT NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
phonenumber VARCHAR(20) NOT NULL,
country VARCHAR(2) NOT NULL,
profession VARCHAR(5000) NOT NULL,
profilepic VARCHAR(5000) NOT NULL,
smskey VARCHAR(100) NOT NULL,
status INT NOT NULL,
reg_date_time DATETIME NOT NULL,
UNIQUE (id,phonenumber))
PARTITION BY HASH(id)
PARTITIONS 1023;";
$this->tb = mysqli_query($this->ret,$this->sql);
if(!$this->tb){
echo "Table not created<br>";
}
else{
echo "Table created<br>";
}
Insert table:
public function table_member_insert($table,$phonenumber="",$username="",$country="",$profession="",$profilepic="0",$smskey="",$status="") {
$this->sql = "INSERT INTO $table
(username,phonenumber,country,profession,profilepic,smskey,status,reg_date_time)
VALUES
('$username','$phonenumber','$country','$profession','$profilepic','$smskey','$status',now());";
$this->tb = mysqli_query($this->ret,$this->sql);
if(!$this->tb){
echo "values not inserted<br>";
}
else{
echo "values inserted<br>";
} }

The problem is that you defined the combination of id and phonenumber fields as unique. Since your id field is defined as auto_increment, it will be unique on its own, therefore any combination with phonenumber field will also be unique.
You need to define the phonenumber field alone as unique. After that you can use insert ignore to insert a new record with an existing phone number without raisin an error. However, pls note that in case of a match, the unique index will prevent the entire record from being inserted.

Related

Foreign Key Failure in MySQL

I have created a database composed of three tables. This is my query in creating my tables with Foreign Key.
CREATE TABLE reporter
(
reporterid INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(1000) NOT NULL,
lastname VARCHAR(100) NOT NULL,
PRIMARY KEY (reporterid)
);
CREATE TABLE flood
(
floodid INT NOT NULL AUTO_INCREMENT,
address VARCHAR(500) NOT NULL,
description VARCHAR(1000) NOT NULL,
dateofflood DATE NOT NULL,
timeofflood INT NOT NULL,
PRIMARY KEY (floodid)
);
CREATE TABLE reports
(
reportid INT NOT NULL AUTO_INCREMENT,
timereport NODATATYPE NOT NULL,
datereport DATE NOT NULL,
rid INT NOT NULL,
fid INT NOT NULL,
PRIMARY KEY (reportid),
FOREIGN KEY (rid) REFERENCES reporter(reporterid),
FOREIGN KEY (fid) REFERENCES flood(floodid)
);
I created a system in order for me to add records/row on my database through PHP. This is my code:
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("flooddatabase")or die("Connection Failed");
$description = $_POST['description'];
$address = $_POST['address']; // Make sure to clean the
$dateofflood=$_POST['dateofflood'];
$timeofflood=$_POST['timeofflood'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$dateofreport=$_POST['dateofreport'];
$timeofreport=$_POST['timeofreport'];
$query = "INSERT into flood(address,description,dateofflood,timeofflood) values ('$address','$description','$dateofflood','$timeofflood')";
$query2 = "INSERT into reporter(firstname,lastname) values ('$firstname','$lastname')";
$query3 = "INSERT into reports(dateofreport,timeofreport) values ('$dateofreport','$timeofreport')";
if(mysql_query($query))
if(mysql_query($query2))
if(mysql_query($query3))
{
echo "";
} else
{
echo "fail";
}
?>
The result that I am getting is fine. It's just that, in my REPORTS table, there is no foreign key that is being generated. For example I input something on my reporter table and flood table, the foreign key 'rid' and 'fid' has no values that references to both tables. Need help thank you.
Get the just inserted Primary key value from flood table insert
query. And store it to a variable say $f_id;
Get the just inserted primary key value from reporter table insert
query and store it to a variable say $r_id;
Now Make your last insert statement like below:
"INSERT into reports(dateofreport,timeofreport,rid,fid) values ('$dateofreport','$timeofreport',$r_id,$f_id)";
I am not giving you a direct copy paste solution.
If you need to know how to get the last inserted id by executing an insert query then look at this link
there is no foreign key that is being generated
I'm not entirely sure what you even mean by that. Foreign keys aren't "generated". Primary keys can be, which you do:
reporterid INT NOT NULL AUTO_INCREMENT
(as well as for your other two tables)
the foreign key 'rid' and 'fid' has no values
Well, look at your query:
INSERT into reports(dateofreport,timeofreport) values ...
Where do you insert values for rid and fid? I'm actually pretty surprised this query works at all, since those columns don't allow NULL values:
rid INT NOT NULL,
fid INT NOT NULL,
(Though your column names also don't line up, so I find it likely that the code you're showing isn't actually the code you're using...) That point aside however, the fact still remains that if you want a value in those fields then you have to put a value in those fields:
INSERT into reports(dateofreport,timeofreport,rid,fid) values ...
After each query, you can get the last generated identifier from mysql_insert_id():
$last_id = mysql_insert_id();
Use that to then populate the values being inserted as foreign keys in subsequent queries.
Also worth noting, the mysql_* libraries are long since deprecated and have been replaced with mysqli_ and other libraries such as PDO. I highly recommend you upgrade to a current technology, since what you're using isn't supported by any vendor.
Additionally, and this is very important, your code is wide open to SQL injection attacks. This basically means that you execute any code your users send you. You should treat user input as values, not as executable code. This is a good place to start reading on the subject, as is this.

Update if record doesn't exist in MySQL DB

This is my table: (the unique main key is alias)
$sql = "CREATE TABLE IF NOT EXISTS Articls
(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(254) COLLATE utf8_persian_ci NOT NULL,
alias INT(10) UNSIGNED NOT NULL, # alias name for url
title VARCHAR(254) NOT NULL COLLATE utf8_persian_ci NOT NULL,
UNIQUE (alias)
) DEFAULT COLLATE utf8_persian_ci";
So I want to insert a new record to the DB if alias does not exist in the table or update the table if the alias already existed before.
I tried this without success.
$sqlname = "name,alias,title";
$sqlValue = "'".$node['name']."','".$node['alias']."','".$node['title']."'";
$sql = "INSERT INTO Articls (".$sqlname.")
VALUES (".$sqlValue.")
ON DUPLICATE KEY UPDATE
(".$sqlname.") VALUES (".$sqlValue.")";
I also tried this code with no success... It just creates a new record and doesn't update:
$sql = "INSERT INTO Articls (".$sqlname.")
VALUES (".$sqlValue.")
ON DUPLICATE KEY UPDATE title = 'test',alias = '".$node['alias']."'";
The synthax:
ON DUPLICATE KEY UPDATE
(".$sqlname.") VALUES (".$sqlValue.")";
is not correct.
Use:
ON DUPLICATE KEY UPDATE <fieldname> = <fieldvalue>, <fieldname> = <fieldvalue>...

Can't insert values to foreign key attribute in php

These are my tables:
create table sender(
sno varchar(6) not null,
sfname varchar(15) not null,
slname varchar(10) not null,
sphone varchar(10),
saddress varchar(40) not null,
constraint pk_sender primary key(sno)
);
create table courier(
cno varchar(6),
cost double precision not null,
weight double precision not null,
del_stat varchar(20) not null,
no_cour int(10),
sno varchar(6),
constraint fk_courier foreign key(sno)
references sender(sno),constraint pk_courier primary key(cno)
);
And this is my php code:
<?php
session_start();
$_SESSION['x']=$_POST[sno];
$con=mysqli_connect("localhost","root","project123","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="insert into sender(sno,sfname,slname,sphone,saddress) values (concat('SN','$_POST[sno]'),'$_POST[sf]','$_POST[sl]','$_POST[sph]','$_POST[sad]')";
$sql2="insert into courier(cno,cost,weight,del_stat,no_cour) values (concat('CN','$_POST[cno]'),'$_POST[cst]','$_POST[wght]','$_POST[del]','$_POST[num]')";
if(!mysqli_query($con,$sql1) && !mysqli_query($con,$sql2))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
But I'm getting error
Error: Cannot add or update a child row: a foreign key constraint fails (project.courier, CONSTRAINT fk_courier FOREIGN KEY (sno) REFERENCES sender (sno))
So please tell me how to insert values to foreign key.
It seems that you're not setting the foreign key value on your child table insert. Your courier table have a column sno VARCHAR(6) that references sender.sno VARCHAR(6) right? So you have to provide it value. In order to relate two fields as foreign key, you have to set a valid value for the child column existing on the parent related column.
Anyway, you should run those two queries like this:
$sno = "SN$_POST[sno]";
$cno = "CN$_POST[cno]";
$sql1="insert into sender(sno,sfname,slname,sphone,saddress) values ('$sno','$_POST[sf]','$_POST[sl]','$_POST[sph]','$_POST[sad]')";
if(mysqli_query($con,$sql1))
{
$sql2="insert into courier(cno,cost,weight,del_stat,no_cour, sno) values ('$cno','$_POST[cst]','$_POST[wght]','$_POST[del]','$_POST[num]', '$sno')";
if (mysqli_query($con,$sql2))
{
// Success
}
else
{
die('Error on query 2: ' . mysqli_error($con));
}
}
else
{
die('Error on query 1: ' . mysqli_error($con));
}
You can see here how to get the last inserted id from an auto_increment field. If you're not using an auto_increment field, you have to select it in other way that fits your needs.
I hope this helps.
UPDATE: I have change those variables sno and cno because you can avoid concatenating it inside your query. You can do that that way. I realize that you already have the sno value, so you don't need to query again after it. That code may now work.

How would I be able to duplicate my auto_increment? DATABASE PHP

Hey how would I be able to duplicate my only auto increment key to another key, basically I want my (' id ') to display the same information on my (' user_id '), here is the code:
CREATE TABLE IF NOT EXISTS `".$db_table_prefix."users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(10) NOT NULL,
`user_name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`id`)
How would I be able to input the same information from my id to my user_id?
Not sure what you mean but if you want to have the same value repeted two times in the same record It's pointless and redundant.
You can use the SQL aliases to achive what you want:
SELECT id as user_id FROM ...
If you really need to sync up the two field of your table you can do:
UPDATE table SET user_id = id WHERE user_id != id
Not sure why you would want to do this, but if you want to duplicate the information after an INSERT you would need to fetch the new ID and then perform an UPDATE
// get the newly inserted ID
$new_id = $db->insert_id;
// perform the update on the table
$db->query("UPDATE users SET user_id=".$db->escape($new_id)." WHERE id=".$db->escape($new_id));
Also, in your table definition the fields don't match: int(11) vs. int(10).

mySQL DB: Making simultaneous entries?

Consider the following tables for a LMS:
Item (
ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT,
ConnectLog BIGINT NOT NULL,
ItemClass BIGINT NOT NULL,
ItemType BIGINT NOT NULL,
AcqDate TIMESTAMP NOT NULL DEFAULT NOW(),
Vendor BIGINT NOT NULL,
Cost DECIMAL(64,2) NOT NULL DEFAULT '0.00',
Image VARCHAR(255),
Access INTEGER NOT NULL,
Notes VARCHAR(255),
PRIMARY KEY (ID)
)
Book (
ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT,
Item BIGINT NOT NULL UNIQUE,
ISBN BIGINT,
Title VARCHAR(255) NOT NULL,
Authors VARCHAR(255),
Publisher VARCHAR(255),
DDC VARCHAR(255),
PubDate DATETIME,
Edition VARCHAR(255),
BookCase VARCHAR(255),
Shelf VARCHAR(255),
PRIMARY KEY (ID)
)
Now when a user makes an entry for Book, first an entry for Item has to be created first. But i need to find the ID for the Item entry that was created so i can use that value for Item in the Book table...
How? :/
Use mysql_insert_id()
// Create Entry
$sql = "INSERT INTO TABLE () VALUES()";
mysql_query($sql);
$id = mysql_insert_id();
// Create Book
$sql = "INSERT INTO TABLE (`Item_ID`) VALUES(".$id.")";
mysql_query($sql);
I bet there is a MySQL Command you could use to do it in a single query. But, this works.
According to this link, you could do an SQL query like:
INSERT INTO foo (auto,text) VALUES(NULL,'text'); # generate ID by inserting NULL
INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text'); # use ID in second table
I haven't tested it, but it seems as though LAST_INSERT_ID() contains the last inserted ID, no matter what table it was inserted into.
If you're worried about heavy loads, and LAST_INSERT_ID() not containing the appropriate entry's ID, you could wrap these SQL statements in a transaction.

Categories