Inserting data into Mysql with multiple unique keys - php

My MYSQL query
$db->query("INSERT INTO customers (first_name,last_name,address,city,state,zip,phone,dnc,user_id)
VALUES ('$firstname','$lastname','$address','$city','$state','$zip','$phone','$dnc','$userid') ON DUPLICATE KEY UPDATE phone=phone");
What I am doing is putting customer information into a database. I Wanted to make sure that each customer was inserted once into the database. This query works for that by using the phone numbers as a unique key. Now the problem I'm having is I want to be able to have duplicates of customers in the database, but no duplicates of customers per user.
In my application multiple users have customers that they have added, but they can't see customer's that other users have added. I want the query to NOT insert only if the user_id and the phone are already in the database. I tried adding
phone=phone AND user_id=$userid
to the end of the query but Haven't been able to get it to work right.
Any help would be appreciated, thanks.

Use this query to add UNIQUE index above both fields:
ALTER TABLE customers ADD UNIQUE `unique_customer` ( user_id , phone)

Related

Update MYSQL Table if Name is Already In the DB

I have a database that stores user details, I want users to be able to update their details if their name matches.
Currently I submit details to the database like this:
$sql="INSERT INTO gdpr_info (name, email, phone, comments, phoneout, emailout, postout, phonein, emailin, postin) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."', '".$comments."','".$phoneout."','".$emailout."','".$postout."','".$phonein."','".$emailin."','".$postin."')";
How would I go about updating the user row ONLY if the name matches for example if a user called 'Robbie Fowler' wanted to update his email he would go to the form, type his name and anything else he puts in after would update his row instead of creating a new row.
I've seen the duplicate key option, but on the form there are checkboxes so I'm worried that if I use that most of the forms will have at least one duplicate key due to the checkbox and it will update the wrong row.
Can you specific which column must be duplicated to update the row?
If he is the user want to update his details I guess you the use the mysql update query to update how this will done is
First fetch the user from the db . The user can be the logged in user who wants to update
Then update the email column like this
UPDATE table-name SET column ='.$_POST['newvalue'].' WHERE namecolumn ='.$loggedINuser.';
Or if you want to change the bame as you said in the question with the name input and the new email then
UPDATE table-name SET column ='..$_POST['newvalue'].' WHERE namecolumn ='.$_POST['name'].';
And also I guess there can be only one primary fields in a table so just look for that the You can have multiple unique columns but one primary column (id column is recommended for that )
Hope this will work

Display original and duplicate data from MySQL

I have a table with the following columns:
id
name
mail
There is lot of data in this table and chances of duplicate data is very high.
I want to display original data row and duplicate data row one after other so that user can delete duplicate data on clicking delete button.
if you select the data and only order them by email address, the original and the duplicates will come together. The rest of the logic can be covered in PHP too.
First of all there is no provision to detect original and dubplicate records in my sql. group by can give u dublicate entry of same record if any there.
You can use group by mail having count(id) > 1 in your select query to find out the records which are duplicate. Then you can use this query result as sub query and find out all records which are duplicate and order them base on mail.

Issues trying to add record to MS Access table in PHP

I have 3 tables in my Access database - Customers, Computers, and Issues for a computer repair PHP application. The definitions for the tables are as follows:
Customers - ID (Autonumber), LastName, FirstName, Telephone
Computers - ID (Autonumber), Model, LogIn, Password, CustomerID (foreign key)
Issues - ID (Autonumber), DateRequested, CustomerID (foreign key), ComputerID (foreign key), Issue
I have a query that adds a customer record followed by a query to retrieve the ID of this new record.
Next, I have a query which adds a new computer record, using the customer ID. Again, I have a query to retrieve the ID of this new record.
Both of these pairs of queries work fine. When I try to insert a new record into the Issues table using the 2 IDs from the previous retrievals, I get an error saying "Microsoft Access can't append all the records in the append query due to key violations. Here is the query I am trying to run:
INSERT INTO Issues (DateRequested, CustomerID, ComputerID, Issue, ItemsIncl, ImageName) VALUES (#1/14/2015#, 1, 1, 'Trouble with monitor.', '', 'none.gif')
I have check both the Customer and Computer tables, and they both contain ID with value of 1. I have also tried changing the date to be included within quotes and get the same problem.
I would appreciate anyone who can help me on this.
Chris
I just figured out one of the issues. I was looking at the wrong set of keys. I also have, within the Issues table, a field for the status which is a number from 1-6. I then added a relationship with the Status table, but I had forgotten to add the different status values.
Sorry about that everyone.

Insert INTO queries using WHERE clause

I have issue on INSERT INTO query,
In the registration form, when user enter username and select the department/center as bursary,
I want to insert that UserName into table bursary.
What I tried is;
$query14 = "INSERT INTO bursary (UserName) VALUES
('$UserName') WHERE DepartCent='Bursary'";
$result14=mysql_query($query14);
My table name is bursary, and it's look like ;
UserID UserName
1 ( ) <---- I want only UserName that choose department/center as bursary
Please anyone help me to solve this, appreciate that.
INSERT queries imply adding data that isn't there already. If you want to insert a value derived from a query you need to use an actual query to get it. The WHERE clause fails because there no row to examine until you insert one.
There's really not enough info to figure out what you're trying to do, but if we just go on this part of your question:
"I want only UserName that choose department/center as bursary"
Then you are probably looking for an INSERT..SELECT (assumes you have already inserted the data into some other user table 'your_user_table')
INSERT INTO bursary(UserName)
SELECT UserName from your_user_table
WHERE DepartCent='Bursary';
You can either:
insert new rows in a database table
update existing rows in a database table
Only when you are trying to change values of existing rows does it make sense to specify a WHERE clause to let the database know which values you want to change.
EDIT: Could you explain again what it is exactly that you are trying to achieve? Do you want to insert only some users filling out your form? Namely those that choose bursary as their department?
Why don't you change your table structure to something like:
Table DEPARTMENT:
Department Name, Department ID
Table USER:
User Name, Department ID (foreign key to Department)
EDIT Nr. 2: The way to do that is by normalizing your Table structure. Suppose one of the following things happened:
You want to add an additional department later on - you would not want to create a new table for that every time.
You want to change the name of a department - do you want to rename your tables? change your code,... I doubt that
So the way to go is to design your tables in a way that they separate the different "things" in your program. One type of thing you are working with are departments (bursary,...) another type of thing are Users. As a rough starting point try to make a table for each and try to connect the tables with so called foreign keys. Read it like this:
Every department has a unique department ID
Every User is associated to a department by this users Department-ID
You can then later on join these tables to find out all users of department X,...
Select u.userName,d.departmentName from User u INNER JOIN Department d ON
u.departmentId=d.departmentId
This would show you the names of all your users and their associated departmentName

Mysql tables relationships / Foreign key?

I'm having a hard time figuring how to link database rows in a PHP / MySql project. My order submission script currently splits information and stores it into 2 tables.
The first one is called "Orders" and contains:
$OrderId, $CustomerName, $CustomerEmail, $OrderTotal, $OrderTaxes
//and other infos about the ORDER
The second one is called "Items" and contains all the BOUGHT products infos:
$ProductId, $OrderedQty
//for each one and such...
It has to be this way because the "Items" table will be searched by different "departments" who will only be shown the parts of the orders they are responsible for.
But they all have to get the "Orders" infos for shipping purposes.
Knowing that the "OrderId" column is a primary key generated on the "Orders" table itself, and that my INSERT TO commands are both executed at the same time, how can I link an "Order Id" column in both tables ?
Do I have to generate some random key to match them ?
If I were to use a foreign key, how would the database know which product goes with which order since they are submited at the same time ?
Or is it fast enough to INSERT in "Orders" -> SELECT $OrderID -> INSERT in "Items" ?
How does one usually do this ? Can't figure this one out.
Thanks in advance for your precious help!
The bought product info should have an extra column the bought product tables called orderid, so you know which products belong to which order.
As for the inserting in to the database this depends on what you are using to execute the queries. Some query classes allow you to run multiple query statements in one go, if this is the case you could run something similar to:
INSERT INTO Orders (OrderId, CustomerName, CustomerEmail, OrderTotal, OrderTaxes) Values(...)
SET #order_id = LAST_INSERT_ID();
INSERT INTO boughtItems (OrderId,ProductId,OrderedQty) Values (#order_id, :productid_1, :name_1),(#order_id, :productid_2, :name_2),(#order_id, :productid_3, :name_3) ....
In order cases you would need to run the insert statement on orders and then obtain the primary key.
Take a look at these links:
In other cases you could use a class which allows you to obtain the last inserted id. This id is connection bound so should give no issues (as long as the insert works, you are not doing multiple inserts in one query, do rollbacks or other weird stuff).
In this case you would do an insert and then call a secondary function to get the inserted id.
See these links:
mysqli insert id
pdo last insert id
mysql insert id
Alternatively you could also execute 2 queries. First the insert query followed by this query:
SELECT LAST_INSERT_ID() as id;
Other related links:
mysql - last_insert_id function
Related post on dba stackexchange

Categories