Method for inserting data into two tables:
We do transfer the 2nd table in our Database.
I made a separate connection for two tables.
table name is transaction_held_record
The columns that I need to fill-in was:
transaction_desc
product_code
product_name
selling-price
Here's the sample code for the first table:
include("system/connxn.php");
if (!isset($_POST['eid'])) customError("Failed: Invalid access.", $log);
//Columns for first table.
$eid = $_POST['eid'];
$customer = $_POST['customer'];
$title = $_POST['title'];
$startTime = $_POST['startTime'];
$endTime = $_POST['endTime'];
$roomID = $_POST['roomID'];
$personnel = $_POST['personnel'];
$service = $_POST['service'];
$status = $_POST['status'];
$remarks = $_POST['remarks'];
$adjustment = $_POST['adjustment'];
$totalprice = $_POST['totalprice'];
$query_str = "UPDATE reservationlist SET `title` = '$title', `start` = '$startTime', `end` = '$endTime', `customer` = '$customer', `resource` = '$roomID', `personnel` = '$personnel', `services` = '$service', `status` = '$status', `remarks` = '$remarks', `totalprice` = '$totalprice', `modflag` = '$adjustment' WHERE id = $eid";
//echo $query_str;
mysql_query($query_str) or customError("Failed: (".mysql_errno().") ".mysql_error(), $log);
//echo mysql_insert_id();
$log->writelog("Update on table [reservationlist] record id: ".$eid);
echo "Saved";
Thank you guys!
You may create A PHP class with two(2) functions. One function that receives arguments(parameters) for the values to be updated by record id to the first table and another function for the other table. for example:
class dbUpdates
{
function updateReservations($eid, $val1, $val2, $val3, $val4, $val5) {
mysql_query("UPDATE reservationlist SET ... WHERE id = $eid");
//do handling or some additional codes here...
}
function insertTransaction($recid, $val1, $val2, $val3, $val4, $val5) {
mysql_query("INSERT INTO transaction_held_record (reffield, val1field, val2field, val3field, val4field, val5field) VALUES($recid, $val1, $val2, $val3, $val4, $val5)");
//do handling or some additional codes here...
}
}
Include the class file include("dbUpdates.php");
Instantiate the class by
$updateDB = new dbUpdates;
and you may call the functions $updateDB->updateReservations("your arguments here..."); and $updateDB->insertTransaction("your arguments here...");
hope this helps a bit...
Correct me if I'm wrong.You need to insert data into two different tables, in two different databases?
for this you need two connection and an script for each one. check if the first script has succeeded then run the second.
but if you could somehow access both tables with one connection, you could run both your scripts in one action!
UPDATE: I think you need to get the ID of the inserted row in first table and use that for second table, right?
do like this : How to get the ID of INSERTed row in mysql?
UPDATE: you can do multiple update, insert query you want done in a single action.like:
$query = "UPDATE `tbl_something` SET col1 = 'first' WHERE col1 LIKE '%something%';INSERT INTO tbl_another (col1 , col2 , col5) VALUES ('firstValue' , 'secondValue' , 'fifthValue');UPDATE ... ; ";
then run it with mysq_query($query);
if you want you can get the id of effected row in the query, like I mentioned earlier and use it in the next one.
hope this helped
Related
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
So, I've got a few txt files, each container around 400,000 lines.
Each line is a word, I need to add to my database, if it isn't in there already.
Currently my code for checking/adding every word is
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
if($num == '0'){
$length = strlen($word);
$timestamp = time();
#mysql_sql("INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ('{$word}', '{$length}', '{$timestamp}')");
}
and the functions being called are:
function mysql_sql($sql){
global $db;
$result = $db->query($sql);
return $result;
}
function mysql_num($result){
return $result->num_rows;
}
I'm looking for a better way to insert each word into the database.
Any ideas would be greatly appreciated.
I can think of some ways to do this.
First, if you have access to the MySQL server's file system you can use LOAD DATA INFILE to create a new table, then do an insert from that new table into your word_list table. This will most likely be your fastest option.
Second (if you don't have access to the MySQL server's file system), put a primary key or unique index on word_list.word. Then get rid of your SELECT query and use INSERT IGNORE INTO word_list .... That will allow MySQL automatically to skip the duplicate items without any need for you to do it with a query/insert operation.
Third, if your table uses an access method that handles transactions (InnoDB, not MyISAM), issue a BEGIN; statement before you start your insert loop. Then every couple of hundred rows issue COMMIT;BEGIN; . Then at the end issue COMMIT;. This will wrap your operations in multirow transactions so will speed things up a lot.
Try out this code. It will first create query with all your values and you will run query only ONCE ... Not again and again for ever row
$values = array();
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
$insert_query = "INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ";
if ($num == '0') {
$length = strlen($word);
$timestamp = time();
$values[] = "('$word', '$length', '$timestamp')";
}
$insert_query .= implode(', ', $values);
#mysql_sql($insert_query);
I am using the following to update a table in my db with various values (I have shortened this example to two). Given an array of users ($user_set) I check to see if settings for the user exist... if they do I update the users row... if they do not then I create a row for the user.
The code below works fine, however, I need to return an array of the rows I just changed so I can update the page display with js.
Essentially what I want to do is $result_array[] = $stmt->execute($binding); (all values of the row updated/inserted)
This way I could echo json_encode($result_array); and have an array of all rows I just updated/inserted for use with js.
Is something like this possible or will I need to create the array on my own in php to return?
<?php
//set bindings
$binding = array(
'one' => $settings['one'],
'two' => $settings['two'],
'user_id' => $user['user_id']
);
foreach($user_set as $key)
{
// check if program settings exist or not
$stmt = $db->prepare("SELECT * FROM settings WHERE user_id = ?");
$stmt->execute(array($key['user_id']));
// program_settings result is
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// if result then settings exist and update... if not insert one
if($result)
{
//prepare update statement
$stmt = $db->prepare("UPDATE settings SET one = :one, two = :two WHERE user_id = :user_id");
}
else
{
//prepare insert statement
$stmt = $db->prepare("INSERT INTO settings (user_id, one, two) VALUES (:user_id, :one, :two)");
}
//set comp id
$binding['user_id'] = $key['user_id'];
// execute the update
$stmt->execute($binding);
}
?>
After you use a stmt->execute(); to execute some sql, you can use stmt->fetchAll(); to take all of the rows that has been affected by your sql statement.
I'm currently creating some sort of inventory system.
I have master_tbl where in I save the items. In master_tbl, I have column qty_left or the available stock left.
I also have the table issuance_tbl where in I save all the transaction in issuing items.
In this table there is issued_qty.
My problem is how can I INSERT a row into issuance_tbl at the same time UPDATE the master_tbl.qty_left. (master_tbl.qty_left - issuance_tbl.issued_qty).
Is it possible?
I think the best way is using Stored Procedure. You can have bunch of SQL statements with error handling and ACID transactions in one place. This is because if your first query executes and the second fails, you may need to rollback transactions. Stored procedures allow all this fancy but reliable stuff.
You can start here: http://forums.mysql.com/read.php?98,358569
I'm not completely confident that 'If there's any way to do such thing':
You need to do it in steps, LIKE THIS:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
Hope this might help
here is the example:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);
I want to edit a table from my database.That table have many data.
I will show sample.Do I need to write many mysql update statement?Have other method to write a only one statement? I am beginner for php? Thank all my friend.Sorry for my english.
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle2',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext2',
WHERE `id` ='$id2';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle3',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext3',
WHERE `id` ='$id3';");
etc.............
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle30',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext30',
WHERE `id` ='$id30';");
You want to update multiple rows from one table with specific data, so bad news you have to do it one by one.... but you can improve your code. If I where you I will create a function and I just call it, something like
function update_my_data($movilefilltex1,$id1){
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
.......
}
So to make the multiple insert you can call update_my_data(value1,valu2) the times that you need. for example in a loop or just whenever you need it.
If there is a UNIQUE index on id (and there will be if it's your PRIMARY KEY), you could use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext) VALUES
('$id1', '$mobiletitle1', 1, '$mobilefulltext1'),
('$id2', '$mobiletitle2', 1, '$mobilefulltext2'),
-- etc.
ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext);
Note that this will, of course, insert new records if they don't already exist; whereas your multiple-UPDATE command approach will not (it would raise an error instead).
In either case, you could build/execute the SQL dynamically from within a loop in PHP.
I would also caution that you would be well advised to consider passing your variables to MySQL as parameters to a prepared statement, especially if the content of those variables is outside of your control (as you might be vulnerable to SQL injection). If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Putting it all together (using PDO instead of the deprecated MySQL extension that you were using):
for ($i = 1; $i <= 30; $i++) {
$sqls[] = '(?, ?, 1, ?)';
$arr[] = ${"id$i"};
$arr[] = ${"mobiletitle$i"};
$arr[] = ${"mobilefulltext$i"};
}
$sql = 'INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext)
VALUES
' . implode(',', $sqls)
. 'ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext)';
$db = new PDO("mysql:dbname=$db", $user, $password);
$qry = $db->prepare($sql);
$qry->execute($arr);
Note that you might also consider storing your 1..30 variables in arrays.
update table1,table2 SET table1.column1 = 'valueX',table2.coulumn2 = 'valueX' where table1.column = table2.coulumn2 ;