I have a mysql table (my_table) which have 3 columns (Name, Age, Place). I have a new text file (data.txt tab separated data file) which have have 2 columns (Name and Place). I want to insert information from file "data.txt" into my_table with the condition if Name is same (in mysql table and in text file "data.txt") update row (insert Place value in 3rd column) otherwise create new row (in which Age will be NULL).
if NAME_my_tabe== Name_data.txt --> update this row (do Place_my_tabe = Place_data.txt)
if Name_data.txt not present in my_tabe --> create new row (do Name_my_table=Name_data.txt, Age_my_table=NULL, Place_my_tabe = Place_data.txt)
How to do this in mysql ??? (I want to insert values from text file)
First of all, make sure your table contains the following:
UNIQUE on Name
Age is NULLABLE
The following query will do what you need:
INSERT INTO my_table SET name = 'Name', place = 'Place'
ON DUPLICATE KEY UPDATE place = 'New Place'
With the code to read your file, you could use:
$file = new SplFileObject('data.txt');
while($file->eof() === true) {
$line = $file->fgets();
$data = explode("\t", $line);
// execute query:
$query = sprintf(
"INSERT INTO my_table SET name = '%1$s', place = '%2$s' ON DUPLICATE KEY UPDATE place = '%2$s'",
$data[0], // escape this
$data[1] // escape this
);
}
Note that you will need to execute that query using your mysql client library.
Related
I am inserting a single row into a table, one of the columns though needs the lastInsertID to append another column. We are building file names off of record IDs. Instead of doing a 2nd update to the newly inserted record, is it possible to get the value of the ID column and append to it in the same mysql insert?
Using PHP, currently I am doing:
$query = "INSERT INTO table (id,idName) values (null,?)" ;
list($lastID,$inError,$inResult) = dbInsert($query,array("")) ;
Then:
$appString = $lastID . "-S1001.pdf" ;
$query = "UPDATE table SET idName=? WHERE id=?" ;
list($upCount,$upError) = dbUpdate($query,array($appString,$lastID)) ;
But is there a way to merge the INSERT and UPDATE into a single statment?
$apString = "-S1001.pdf" ;
$query = "INSERT INTO table (id,idName) values (null,id.$appString)" ;
list($lastID,$inError,$inResult) = dbInsert($query,array()) ;
Why not create a trigger that will do your update whenever you insert a row into the table?
This way, you don't need to manually do the second query. Just the insert.
Sorry if this has been asked before, but I couldnt find anything that would relate to my case here on SE.
I am trying to import a CSV file into my Mysql database table with both the table the CSV having the exact same amount and order of columns, except that the table's column ID is not missing in the CSV file.
What I want to achieve is to import the CSV into the table while generating an ID number that automatically increases with each record. This does not seem possible as the CSV always seem to want to insert its data into the first colum in the table, but in my case I would need it to be the 2nd column.
How do I approach this and is there any reference code I can study? I currently am working off this PDO approach but am having the above mentioned difficulties.
PHP
<?php
$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";
if(!file_exists($csvfile)) {
die("File not found. Make sure you specified the correct path.");
}
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator));
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
Thank you
You can have MySQL set values for certain columns during import. If your id field is set to auto increment, you can set it to null during import and MySQL will then assign incrementing values to it.
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator))."
SET id=null;
EDIT - In case the ID column is not present in CSV
The col1, col2, col3,... are names of actual columns in the DB table (without id column)
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator))."
(col1, col2, col3,...)
SET id=null;
The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows. Most version of mysql and engin support this. You need not worry about the ID and can use cron job to insert the needed field and AUTO_INCREMENT will take care of the id itself.
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled. If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers. When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value.
You can retrieve the most recent automatically generated AUTO_INCREMENT value with the LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function. These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts.
See example from official link :
[https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html]
As you want to recreate the table over and over and want to manipulate the Data from the CSV, try this:
// You have to create the TABLE if not exists
$pdo->exec("TRUNCATE TABLE sample"); // No need to drop the table if columns don't change.
$csvContent = file_get_contents($csvfile); // Raw Data from file
$lines = explode("
", $csvContent); // The standard line separator is an ENTER
// Now you have each line separated
for($i = 0; $i < coount($lines); $i++) {
$col = explode(";", $lines[$i]); // Would be a comma
// Now you have each column separated
$pdo->exec("INSERT INTO sample (id, col1, col2, col3 ... coln) VALUES (NULL, '".$col[0]."', '".$col[1]."', '".$col[2]."' ... '".$col[n]."')");
}
This way you can dig into your Data and, besides setting an AUTO_INCREMENT ID, you can validate what is coming from the CSV and can correct/prevent importation errors.
I want to create columns in a MySQL table and insert data into them. I already have some data inside of the table, I would like to add more. I am not sure how I would go about adding the other data. If someone could help me out, I would greatly appreciate it. Thanks.
My Source code looks like this:
if($is_array($asinXML){
foreach($asinXML as $asinXml){
$asinXmlLoaded = simplexml_load_file($asinXml);
foreach($asinXml->GetLowestOfferListingsForASINResult as $asinItem){
if(isset($asinItem['ASIN'])){
$asinValue = $asinItem['ASIN'];
} else {
$asinValue = '';
}
$asinErrorFound = 'Success' != $asinItem->attributes()->status;
if($asinErrorFound = TRUE){
$asinErrorFoundVal = 'Yes';
} else {
$asinErrorFoundVal = '';
}
if($asinErrorFoundVal == ''){
if(isset($asinItem->Product->LowestOfferListing->NumberOfOfferListingsConsidered){
$numberOfSellers = $asinItem->Product->LowestOfferListings->LowestOfferListing->NumberOfOfferListingsConsidered;
} else {
$numberOfSellers = '';
}
My Sql table looks something like this so far :
UPC ASIN SalesRank
Value Value1 Value2
I need to be able to insert a insert another column, then populate the column with information that corresponds to the ASIN Value. If that doesn't make sense, comment and i will elaborate. Thanks.
You can add a column (or columns) using ALTER TABLE statement. e.g.
ALTER TABLE mytable ADD my_new_col INT COMMENT 'my new column' ;
If you want to initialize that column on all of the rows that are already in the table, you can populate it with the value from another column on the row with an UPDATE statement:
UPDATE mytable SET my_new_col = some_old_col ;
If you just want to add a new row to the table, you can use the INSERT statement:
INSERT INTO mytable (my_new_col) VALUES (42);
you can ADD a calculated Column with the desired value.
If ASIN is numeric and you want to add taxes
ALTER TABLE myTable ADD MyNewColumn AS (ASIN * 1.08)
In my form, I have file type input field that is dynamically generated by add more click button.
Everything is ok, when I insert the data but i'm facing problem when I update second table which
I used for only store file type data.
I have analysed some case:
Case 1: if value exist is equal to new value then update
Case 2: if value not exist then insert data
Case 3: if value exist and greater than previous value then update the previous value and insert new data
case 4: if value exist and less than previous value then update previous and other value will be remain same(no change).
I have tried so far
$array_filename = trim($array_filename, ",");
$filename_array = explode(',', $array_filename);
$query = mysql_query("SELECT * FROMtbl_name_2WHEREjob_app_id='$editId' ");
$res = mysql_fetch_array($query);
for($i=0;$i<coun($filename_array);$i++) {
$insertQuery = "REPLACE INTOtbl_name_2(id,job_app_id,file_name) VALUES ('$res[$i]','$editId','$filename_array[$i]')";
$isInsert = mysql_query($insertQuery) or die(mysql_error());
}
mysql update if exist else insert
Should better be described as INSERT ELSE UPDATE - and that's what you can to with the ON DUPLICATE KEY UPDATE keywords and the proper unique key constraints (assuming uniqueKey column to be unique):
INSERT INTO
myTable (`id`, `uniqueKey`, `value2`) VALUES (null,"test1",17)
ON DUPLICATE KEY UPDATE
value2 = 17;
This covers your case 1 and 2: Data is inserted or updated.
For your case 3 and 4 it is unclear, what you are asking? It seems like these statements are targeting multiple tables, or what do you mean by update the previous value and insert new data?
I have a variable which displays the following string:
$item_value = itemOne,itemTwo,itemThree
I would like to take this string and have insert each item as a separate row entry for a single column. Additionally, I need it to insert an auto increment key value for each entry. So to complete this example, here is what I would want the mysql table to look like when complete:
ID || item_value || comments
----------------------------------------
1 || itemOne || --------------
2 || itemTwo || --------------
3 || itemThree || --------------
My feeling is that I need to explode the string around the comma and then insert it into the table. I have attempted this but am having some issues getting each item as separate row entries. Any assistance is much appreciated.
For the auto-increment i suggest letting the database handle it, for mysql just declare it with AUTO_INCREMENT on the id field, for postgres you can set the data type to serial, as for separating each line use the php explode function
here's a little example
<?php
$dbh = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$query = "INSERT into my_table (item_value) VALUES (?)";
$data = 'itemOne,itemTwo,itemThree,itemFour';
$st = $dbh->prepare($query);
foreach(explode(',', $data) as $r) {
// user array($r) for php 5.3 or lower
$st->execute([$r]);
}
This uses PDO which is the recommended method for handling database connections
Something like this should split them up and give the option for insertion in the db:
<?php
$item_value = 'itemOne,itemTwo,itemThree';
$item_array = explode(",",$item_value);
foreach($item_array as $key => $value){
// insert into the db here
$query = "INSERT INTO table_name set item_value = '".mysql_real_escape_string($value)."', ID = '".($key + 1)."'";
// however you choose to connect and insert into the database goes here :)
}
?>