SQL QUERY for inserting a record into PHPMyadmin - php

What I am trying to achieve is a SQL query which will insert a new product in the product table which has an auto incremented product_id value. However, in the customer table there is also a column for product_id which is a foreign key referencing the product_id value in the product table. Now, I can insert a new product and a new customer, but I would like to know how to write a script that takes a query which I can use in a PHP script which will allow a customer insert a new product so that the keys will relate automatically, so one customer can be related to many products.
I have tried the references in the PHP manual.
$query = mysql_query (" INSERT INTO events
VALUES
( '',
'$event_type',
'$title',
'$description',
'$date',
'$target',
'$add1',
'$add2',
'$ci‌​ty',
'$postcode',
'$country',
'$tick',
NULL
)"
);
For example I have got an events table for the above query and the NULL value at the end of the query is for the foreign key column (user_id) which is from the user table...
If I was a user inserting the event how would I add my id to the event?

First thing is that you should think about your database-model. Is it right, that one customer has got one foreign key to a product? It conflicts that you say that one customer can be related to many products.
Anyway; your problem is, that you insert a product and the ID is automatically generated so you don't know about it, right? You have to write it, read it out right afterwards to make your next insertion. I would recommend a stored procedure to handle this, because your PHP-script should not communicate with your Database as much as this.

Related

How to write Insert and Update query in one single Query in mysql

I have below mentioned Issue.
I am developing inventory system using php.
According to that i have to add invoiced items to table.
Dynamically generated text box used to collect received item details.
I have current_stock table and it contain Item-name and qty columns.
Item-name is primary key field.
item which i am going to insert if already exist quantity should be updated with new value.
if it is not exist should be inserted as a new row.
This is must be done in loop because i use dynamically genarated text box and data collect using $item[] and $qty[] arrays.
I am try to use several ways to solve this issue unable to execute in for loop but not yet success.
please help me.........
you can try this :
INSERT INTO table (id, item_name, qty) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
item_name="A"
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.
for multiple query excution you have to use
mysqli_multi_query()
like this :
mysqli_multi_query("INSERT INTO TABLE SET Field='Value',FieldB='ValueB';
UPDATE TABLE SET Field='Value',FieldB='ValueB' WHERE FIELDID='VALUEID';")
i hope this will work.have fun.

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

MySQL Update if value exists, Insert if not in PHP?

$sql_career = "REPLACE INTO career
(id, battletag, lastHeroPlayed, lastUpdated, monsters, elites, hardcoreMonsters, barbarian, crusader, demonhunter, monk, witchdoctor, wizard, paragonLevel, paragonLevelHardcore)
VALUES
('', '$battletag', '$lastHeroPlayed', '$lastUpdated', '$monsters', '$elites', '$hardcoreMonsters', '$barbarian', '$crusader', '$demonhunter', '$monk', '$witchdoctor', '$wizard', '$paragonLevel', '$paragonLevelHardcore')";
ID auto increments.
battletag is unique.
Everything else changes over time. So I want to replace or update an entry if the battletag already exists without it making a new id. If it doesnt exist I want it to make a new entry letting the id auto increment for that unique battletag.
This works with one problem:
$sql_career = "
insert INTO career
(id, battletag, lastHeroPlayed)
VALUES
(NULL, '$battletag', $lastHeroPlayed)
on duplicate key
update lastHeroPlayed=$lastHeroPlayed;
";
If I, for instance, load in two unique rows, the ID auto increments to 1 and then 2 for each. Then if I load up a row that has a duplicate of the unique key of one of the existing rows (and it then updates as it should) this actually triggers the auto increment. So if I then add in a third unique row, its number will be 4 instead of 3.
How can I fix this?
You want to use the on duplicate key ... update syntax instead of replace into.
Define a unique column (primary or unique index) then check it in your statement like this:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
The benefit of using this over a replace into is that replace into will always delete the data you have already and replace it (sort of as the command name implies) with the data that you are supplying the second time round. An update on... statement however will only update the columns you define in the second part of it - if the duplicate is found - so you can keep information in the columns you want to keep it in.
Basically your command will look something like this (Abbreviated for important columns only)
$sql_career = "
insert INTO career
(id, battletag, heroesKilled)
VALUES
($id, '$battletag', $heroesKilled)
on duplicate key
update heroesKilled=heroesKilled+1;
";
Again, remember that in your table, you will need to enforce a unique column on battletag - either a primary key or unique index. You can do this once via code or via something like phpMyAdmin if you have that installed.
Edit: Okay, I potentially found a little gem (it's about a third of the way down the page) that might do the trick - never used it myself though, but can you try the following for me?
$sql_career = "
insert ignore INTO career
(id, battletag, heroesKilled)
VALUES
(null, '$battletag', $heroesKilled)
on duplicate key
update heroesKilled=heroesKilled+1;
";
There seems to be collaborating evidence supporting this in this page of the docs as well:
If you use INSERT IGNORE and the row is ignored, the AUTO_INCREMENT counter is not incremented and LAST_INSERT_ID() returns 0, which reflects that no row was inserted.

Inserting into two SQL tables using a value from one

I am building a simple event registration system using MySQL and PHP. I have four tables:
events: event_id, event_name
instance: instance_id, event_id, date
attendee: attendee_id, attendee_name, attendee_email, attendee_tel
registration: reg_id, attendee_id, instance_id
To clarify, the instance table contains instances of a given event, ie a specific event on a specific date.
When an attendee registers (via a form), I want to write their details to the attendee table, then write the event they have registered for in the registration table, along with the relevant attendee_id, so that when I query the registration table later on, it will show me what event has been registered for and by whom.
However, I'm new to SQL (and databases in general, not to mention PHP as well), so I'm not sure how I can do that given that the attendee_id has only just been generated by adding the attendee to the table. I can easily insert a row into the attendee table with:
$q = "INSERT INTO attendee (attendee_name, attendee_email, attendee_tel)
VALUES ( '$fullname', '$email', '$tel' )";
With the values obviously being grabbed by $_POST from the form. The form also grabs the instance_id, incidentally.
So I just need to know how I can insert the relevant information into the registration table. Any ideas?
After inserting the data to the 1st table (attendee), use the php function mysql_insert_id() to get the last auto increment id.
Then run another query to insert the data to the 2nd table (registration).
In such cases, in order to avoid any data mismatch with the two tables, its better to use BEGIN and COMMIT. So that if any MySQL error occurs in between 2nd query, it will automatically role back.
make these column in tables primary key and auto increment
events: event_id
instance: instance_id
attendee: attendee_id
registration: reg_id
and you can get the last inserted id when you run query to insert in these table by following code immediate after the insert query
$id = mysql_insert_id();
use this appropriately
see mysql_insert_id()
The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
If you are using mysql_query() for inserting the data into the attendee table, write the mysql_insert_id() in the next line, it will gives you the recently generated attendee_id, store it in a variable and using this variable insert again in the registration table. Something like that:
$q = "INSERT INTO attendee (attendee_name, attendee_email, attendee_tel) VALUES ( '$fullname', '$email', '$tel' )";
$rc=mysql_query($q);
$a_id=mysql_insert_id();
now insert again in 'registration' table with $a_id;

Update record only if another column matches?

I'm trying to develop a simple tracking system. What I'm trying to do is either insert the new record or update the record IF it matches the same campaign. I want to insert a new record if the user is triggered on a new campaign. Here is my current query that work fine.
INSERT INTO `tracking` (`email`,`ip`,`referrer`,`campaign`,`timestamp`)
VALUES ('$campaign[0]','$ip','$referrer','$campaign[1]','$timestamp')
ON DUPLICATE KEY UPDATE `last_timestamp` = '$timestamp'
My goal is if joe#bob.net triggers campaign1, then it will INSERT the record. If he tries campaign 1 again, it just updates the timestamp. Now when joe#bob.net triggers campaign2, it inserts an entirely new record.
So basically I'm trying to get it to INSERT only when the user triggers a new campaign. Otherwise, I want it to update the timestamp.
Any ideas or advice I'd really appreciate it!
Unless I'm missing something, all you need is a unique key put on the 'email' and 'campaign' columns on your table:
ALTER TABLE tracking ADD UNIQUE KEY uk_email_campaign (email, campaign);
Just add a unique key on (email, campaign) -
ALTER TABLE `tracking`
ADD UNIQUE INDEX `UQ_email_campaign` (`email`, `campaign`);

Categories