comparing two tables while inserting data into database using php mysql - php

category --> `cat_id`,`name`
sub_category --> `sub_cat_id`,`name`
category_subcategory_association --> `cat_sub_cat_id`,`cat_id`,`sub_cat_id`
order_master --> `order_id`,`cat_sub_cat_id`,`cat_id`,`sub_cat_id`,`order_name`
These are the database tables which iam having while adding the orders into order_master table if we give cat_id,sub_cat_id while inserting into the table it should check the whether these ids are present in the association table or not,if the id is present in association table then we should get that association id and should insert into the orders table.
How can we do this can anyone help me
Thanks in advance.

You just need to check if it exists, if not - insert it into the the db and fetch the newest id.
I.E:
$cat_name = ; // your code
$sub_cat_name =; // your code
$query = mysql_query("SELECT cat_id FROM `category` AS `c` WHERE name = '$cat_name'");
if(!mysql_num_rows($query)) {
mysql_query("INSERT INTO category (name) VALUES ('$cat_name')");
$cat_id = mysql_insert_id();
} else
$cat_id = mysql_fetch_array($query);
// now do the same for the sub category and then insert it into to order_master
this is a general code, you need to customize it into your framework's standards.
hope it helped

you implement the checks via a select statement:
http://dev.mysql.com/doc/refman/5.1/de/select.html
running multiple sql queries, eg. a mixture of select and update statements requires you some knowledge on:
http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-model.html
http://php.net/manual/de/mysqli.multi-query.php

Related

How can I insert or update records from different tables

I have two tables: parts (with codice, pezzi, durata) and magazzino (with codiceM, pezziM, durataM)
I want to add or update some records from parts to magazzino. What I would Like to do is:
check if codice is already present in the table magazzino, if not INSERT a record with codice, pezzi and durata.
if codice is already present in magazzino, sum and UPDATE pezzi and durata associated with codice.
I use phprunner to create database and insert a button that executes the code after selecting a record in parts.
Here is my code that execute with no errors but it gaves me no results.
$record = $button->getNextSelectedRecord();
$cod=$record["codice"]; //variable assignments
$qnty=$record["pezzi"];
$time=$record["durata"];
$control=0; //control variable
$con = new mysqli("localhost","root","","provaMagazzino") or die("sorry not connected");
$sql = "SELECT * FROM magazzino";
$resultq = $con->query($sql);
while($row = mysql_fetch_array($resultq)){ // check and update records in magazzino table
echo($row['codice']);
if ($row['codice']==$cod) {
$row['pezziM']+=$qnty;
$row['durataM']+=$time;
echo('durataM');
$control=1;
break;
}
}
if ($control=0) { //add new records al Magazzino if control variable is zero
$resultq->codiceM = $record["codice"];
$resultq->durataM = $record["durata"];
$resultq->pezziM = $record["pezzi"];
$resultq->descrizioneM = $record["descrizione"];
$resultq->Add();
}
You can calculate your data with mysql only
SELECT p.codice, IFNULL(p.pezzi, 0) + IFNULL(m.pezziM,0) AS updatedPezzi,IFNULL(p.durata,0) + IFNULL(m.durataM,0) AS updatedDurata FROM parts AS p
left join magazzino m on p.codice = m.codiceM
IFNULL is added just to be sure that your data will not be lost if the record does not exist in magazzino table.
The result will be data that need to be inserted into magazzino table and you can customize it with WHERE condition to calculate specific rows
After that you can insert this data from php to mysql again if INSERT ON DUPLICATE is not good for you.
There are a lot of cases. As I see the codice column should be unique so for me insert on duplicate key update is the best choice here
Is this correct?
$record = $button->getNextSelectedRecord();
$cod=$record["codice"]; //variable assignments
$qnty=$record["pezzi"];
$time=$record["durata"];
INSERT INTO magazzino(codiceM, pezziM, durataM)
VALUES ('$cod', '$qnty', '$time')
ON DUPLICATE KEY UPDATE
codiceM= values($cod)
pezziM= pezziM+ values($qnty)
durataM= durataM+ values($time)

INSERT INTO SELECT with VALUES in one query

Bit new to MYSQL and PHP - I have the following code that will create a new record in multiple tables that I have setup however I need to merge the following code together somehow as it creates separate rows instead of one record
$sql .=("INSERT INTO orders (customer_id) SELECT customer_id FROM
customer_details;");
foreach($result as $item){
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$sql .=("INSERT INTO orders(product_description, delivery_mode, course_cost) VALUES('$mysql_desc', '$mysql_mode', '$mysql_cost');");
}
The result I'm getting:
Based on your data I assume that you want to insert the customer id and the values from php into the same record. In this case you need to combine them into the same insert ... select ... statement:
$sql .=("INSERT INTO orders(customer_id, product_description, delivery_mode, course_cost) select customer_id, '$mysql_desc', '$mysql_mode', '$mysql_cost' from customer_details;");
Couple of things to note:
This insert ... select ... statement will insert the same records for all customers in the customer details table. I'm not sure if this is your ultimate goal.
Pls consider the advices made in the comments regarding the old mysql API and the use of prepared statements.
To put this more into what I would expect to happen, something along the lines of - prepare statement, then loop through each item and add in new row...
$insert = $connection->prepare("INSERT INTO orders (customer_id,product_description, delivery_mode, course_cost)
VALUES (?,?,?,?)");
foreach($result as $item){
$customerID = 1; // Have to ensure this is what your after
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$insert->execute([customerID,mysql_desc,mysql_mode,mysql_cost]);
}

Inserting data into multiple tables not functioning correctly

I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement

How to insert multiple MySQL table rows from a PHP array

I'm new to both PHP and MySQL and I have a pretty complicated task to do for my current know-how. It goes like this:
I'm trying to create a data-driven website with a hand made CMS that will allow a user with no knowledge of web design/web development to manage it. Where I'm stuck is when I try to create a query to handle the data inserted to the database. It is a bookstore and I'm inserting books in the database. I thought of creating 3 tables, one to store the books themselves, one to store the categories these books belong to (f.e. literature, mystery, fantasy, etc) and, since the relation between these two tables is many-to-many relationship, I also created a lookup table to link these two, using 2 columns populated with 2 foreign keys representing the IDs of the two tables.
The problem is I can't find how to insert multiple rows with same ID (the book ID) on one column and different second column (the category ID). The categories will be picked in an HTML form via checkboxes. I' ve seen in several posts here I need to make an array in PHP script to store the data from the checkboxes the user picked, but I have absolutely no clue on how to structure the query that will turn these checkboxes into multiple MySQL table rows.
I've seen people suggesting imploding the values, but that would store multiple values in one row, or am I mistaken? Because that is not what I want, I want (if f.e. the user checked 3 categories checkboxes) to create 3 rows in the lookup table.
Thanks in advance for your time seeing my question.
$categories = array(1,2,3,4);
$bookId = 5;
foreach ($categories as $categoryId) {
$data = array(
'book_id' => (int)$bookId,
'category_id' => (int)$categoryId
);
$query = "INSERT INTO `lookup` SET ";
$fields = array();
foreach ($data as $field => $value) {
$fields[] = "`$field` = '$value'";
}
$fields = implode(', ', $fields);
$query .= $fields;
mysql_query($query);
}
You can build up an insert using implode to insert many rows. Something like this:-
<?php
$Category = 123;
$Books = array(1,2,3,4,5,6,7,8,9,10);
$sql = "INSERT INTO book_category_link(NULL, category_id, book_id)
VALUES ($Category".implode("),($category", $Books).")";
?>
Or if you want to use the existing tables to get the ids then something like this:-
<?php
$Category = (123, 456, 789);
$Books = array(1,2,3,4,5,6,7,8,9,10);
$sql = "INSERT INTO book_category_link(NULL, category_id, book_id)
SELECT NULL, categories.id, books.id
FROM books
CROSS JOIN categories
WHERE books.id IN (".implode(",", $Books).")
AND categories.id IN (".implode(",", $Category).")";
?>
It's really simple. First you insert the the book into the books table and then get the ID of it. Let's say for this example it is the ID 5.
Lets say you have the following categorie id's from the checkboxes: array(21, 42, 64);
Now you can construct a query like this to insert them into the lookup table:
INSERT INTO `lookup` (book_id, category_id') VALUES (5, 21), (5, 42), (5, 64);
No, you can't insert into multiple tables in one MySQL command. You can however use transactions.
INSERT ...
SELECT LAST_INSERT_ID() INTO #mysql_variable_here;
INSERT INTO table2 (#mysql_variable_here, ...);
INSERT INTO table3 (#mysql_variable_here, ...);
if you want to add multiple rows inserted then u can use the syntax
INSERT INTO table (col1, col2) VALUES ('value', 'value'), (value, 'value');
The very basic idea is to iterate a loop on the categories submitted and run an insert query containing category ID and book ID into the lookup table.
$bookID= $_POST['bookid'];
foreach ($categories as $category) {
mysql_query("INSERT INTO lookup(bookid,categoryid) values($bookID,$catetory)");
}

php/mysql creating duplicate records with multiple tables

I'm building a database for making hotel reservations. One table called "reservations" holds the general details of the reservation, while another called "rooms" holds details about specific rooms (each reservation has many rooms, each room belongs to only one reservation).
I would like to be able to easily generate duplicate reservations records (except for the primary key, of course). My problem is in generating the rooms data as an array which is then inserted into the rooms table while being associated to its reservation.
I've come as far as the following trivial code (stripped down to the bare essentials for discussion purposes).
if (isset($_POST['action']) and $_POST['action'] == 'Duplicate')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
// retrieve reservation
$sql = "SELECT type_of_reservation FROM reservations WHERE id='$id'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$type_of_reservation = $row['type_of_reservation'];
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
$id = mysqli_insert_id($link);
// retrieve rooms
$sql = "SELECT reservation_id, in_date FROM rooms WHERE reservation_id='$id'";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
$rooms[] = array('reservation_id' => $row['reservation_id'], 'in_date' => $row['in_date']);
}
The big question is, now what? Everything I've tried either generates an error or no new entries, and I can't seem to find any discussion that addresses this specific need. Thanks for your help.
PeterC, there is no code listed that shows you inserting the ROOM record information. In the //retrieve room section of your code, you are pulling the data and putting it into an array. If you really want to create a duplicate records, I would use in insert inside the database, then you don't have to pull the records out just to put them back in.
The bit of code you want will be something like this. It will be in place of the //retrieve rooms code you have listed: (psuedo code) [note: $id represents the newly selected id from your sql insert for the duplicated reservation]
INSERT INTO rooms(res_id, other, data)
SELECT $id, other, data FROM rooms WHERE id = $_POST['id'];
This will allow you to duplicate the room data, adding the new reservation_id right inside the database. No need to pull out the records, create inserts, and then put them back in. You can read more about INSERT INTO ... SELECT statements here: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
//ADD HERE CODE BELOW
$id = mysqli_insert_id($link);
with mysql_insert_id you get the inseted id, but you should insert it into db.. so add
mysqli_query($link, $sql);
before retrieving data
If you simply need to duplicate records, you can do it this way:
INSERT INTO
reservations
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
`all`,
`other`,
`column`,
`names`
FROM
reservations
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)
Then for the rooms use the last inserted id (for instance retrieved with mysql_insert_id), like this:
INSERT INTO
rooms
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
$newReservationId, # this is the new reservation id
`all`,
`other`,
`column`,
`names`
FROM
rooms
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)

Categories