MYSQL copy row to another identical table with AUTO_INCREMENT id field - mysql

I have a movie database where movies are inserted into a table named titles with an AUTO_INCREMENT primary key named titles_id. Users can submit movies anonymously which are inserted into a separate identical table named titles_anon. After reviewing entries in titles_anon I want to insert them into titles but the id column is causing problems
I tried this:
INSERT INTO titles SELECT * FROM titles_anon WHERE
title_id='$title_id';
I either get a duplicate key error, or if the title_id does not already exist in titles it inserts OK but uses the titles_anon id instead of a new AUTO_INCREMENT value which I want.
How do I copy a row between tables when both tables have an AUTO_INCREMENT primary key?

INSERT INTO titles
(column_name1, column_name2, column_name3, column_name4,...)
SELECT title_id, col2, col3, col4,..
FROM titles_anon
WHERE title_id = '$title_id';

You define your fields in SELECT, but omit the PK and add the same fields to INSERT!

You can omit the id column completely, let mysql generate it for you. This need a little longer SQL to specify the exact columns you want to insert.
INSERT INTO titles (columns-other-than-the-primary-key)
SELECT columns-of-the-same-order FROM titles_anon

In PHP you can do something similar to:
$rs = mysql_query("select * from table_orig where RowID=$IDToCopy",$db_conn);
$row = mysql_fetch_assoc($rs);
$sql = '';
$fields = '';
foreach($row as $k => $v){
if($k == "RowID") continue;
$sql .= ",'$v'";
$fields .= ",$k";
}
$sql = "insert into table_copy (".substr($fields,1).") values (".substr($sql,1).")";
mysql_query($sql,$db_conn);

/* copy table with primary key to another table */
$table_old='colaboradores'; // your table old
$table_new='colaboradores2'; //your table new
// sql all columns withou primary key (column_key <> 'pri'
$rs=mysql_query("select column_name from INFORMATION_SCHEMA.COLUMNS
where table_name = '$table_old' and column_key <> 'pri' AND
table_schema = 'your database'");
// get all columns
$rows = mysql_fetch_assoc($rs);
$fields = '';
// mount fields in line
foreach ($rows as $k => $v) {
$fields .= ",$v[0]";
}
// remove first comma
$fields = substr($fields,1);
echo "Sintaxe for Create table in Mysql";
echo "CREATE TABLE $table_new SELECT $fields FROM $table_old ";
echo "Sintaxe for Insert from old table to new table Mysql";
echo "INSERT INTO $table_new $fields SELECT $fields FROM $table_old";

Related

PDO Mysql same query but insert to multiple users [duplicate]

This question already has answers here:
What is the best way to insert multiple rows in PHP PDO MYSQL?
(4 answers)
Closed last year.
I would like through pdo insert multiple (bulk) rows with same value, only diffent is the user_id
I'm passing a array with userIds but i have no idea how to bind them.
<?php
require_once("db.php");
$usersId = $jsonData["usersId"];
$text = $jsonData["text"];
// Try to fetch the user from the database
$query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
$stmt = $db->prepare($query);
// Bind value
$stmt->bindValue(":userId", $userId);
$stmt->bindValue(":text", $text, PDO::PARAM_STR);
// Execute
$result = $stmt->execute();
?>
My Tables:
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
);
INSERT INTO users (name)
VALUES ("Gregor"),
("Liza"),
("Matt"),
("Bob");
CREATE TABLE posts(
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
text VARCHAR(255)
);
You need a loop:
require_once("db.php");
$text = $jsonData["text"];
// Try to fetch the user from the database
$query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
$stmt = $db->prepare($query);
// Bind value
$stmt->bindParam(":userId", $userId);
$stmt->bindValue(":text", $text, PDO::PARAM_STR);
// Execute
foreach ($jsonData["usersId"] as $userId) {
$result = $stmt->execute();
}
Use bindParam() so it binds to a reference to the variable. That allows you to reassign the variable each time through the loop without re-binding.

How to retrieve ID from other table for composite key in another table in mysql

I have 4 tables, tblstaff, tblgrade, tblperformance and tblcategory. In tblperformance, there are 3 keys. perID is a primary key. staffNo and catID are composite keys.
I use catID as auto increment in tblcategory and staffNo, I fill in by myself for tblstaff. My sql statement has no problem when I run the code.
How can I retrieve staffNo and catID from tblstaff and tblcategory to insert in tblperformance using insert statement in sql?
<?php
$staffNo=$_POST['staffNo'];
$staffName=$_POST['staffName'];
$grade=$_POST['grade'];
$gradePosition=$_POST['gradePosition'];
$gradeDepartment=$_POST['gradeDepartment'];
$catTechnical=$_POST['catTechnical'];
$catOtherTechnical=$_POST['catOtherTechnical'];
$catTechnicalDescription=$_POST['catTechnicalDescription'];
$catOtherTechnicalDescription=$_POST['catOtherTechnicalDescription'];
$catWeightage=$_POST['catWeightage'];
$perReqScore=$_POST['perReqScore'];
$perActScore=$_POST['perActScore'];
$perAction=$_POST['perAction'];
$perOtherAction=$_POST['perOtherAction'];
$perTrainingIlsas=$_POST['perTrainingIlsas'];
$perTrainingPublic=$_POST['perTrainingPublic'];
$sql1="INSERT INTO tblstaff(staffNo, staffName)VALUES('$staffNo', '$staffName')";
$result1=mysql_query($sql1);
$sql2="INSERT INTO tblgrade(grade, gradePosition, gradeDepartment)VALUES('$grade', '$gradePosition', '$gradeDepartment')";
$result2=mysql_query($sql2);
$sql3="INSERT INTO tblcategory(catTechnical, catOtherTechnical, catTechnicalDescription, catOtherTechnicalDescription,catWeightage)
VALUES('$catTechnical', '$catOtherTechnical', '$catTechnicalDescription', '$catOtherTechnicalDescription', '$catWeightage')";
$result3=mysql_query($sql3);
$sql4="INSERT INTO tblperformance(perReqScore, perActScore, perAction, perOtherAction, perTrainingIlsas, perTrainingPublic)
VALUES('$perReqScore','$perActScore', '$perAction', '$perOtherAction', '$perTrainingIlsas', '$perTrainingPublic')";
$result4=mysql_query($sql4);
if(($result1 || $result2) || ($result3 || $result4) == TRUE)
{
echo "<script>alert('Data inserted successfully')</script>";
}
else
{
echo "ERROR";
}
?>
To retrieve data, in your case:
$query = "SELECT * FROM tblcategory ORDER BY catID DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$latestCatID = $row["0"];
}
Where SELECT * FROM tblcategory ORDER BY catID DESC LIMIT 1 gives you the last record you inserted.
With staffNo, you can just use $staffNo
Finally, your insert into tblperformance will look like this:
$sql4="INSERT INTO tblperformance(catID, staffNo, perReqScore, perActScore, perAction, perOtherAction, perTrainingIlsas, perTrainingPublic)
VALUES('$latestCatID', '$staffNo', '$perReqScore','$perActScore', '$perAction', '$perOtherAction', '$perTrainingIlsas', '$perTrainingPublic')";
$result4=mysql_query($sql4);
Be careful with '$latestCatID' and '$staffNo', you don't need the single quotes '' if you are using an integer data type.

Insert Rows with using the result from a group of select best way to do it

I have an array of tags inserted in my database, and I need to insert them in another table with itemID and tagID.
The thing is that i don't have the tagID - instead I have a TagName with the name. I need to get the tagID so I can insert it afterward, but I'm wondering if this is possible to achieve in one single query.
I mean search for the name, then get its tagID and then insert it the array, or even inserting them one by one would work.
if I understood you, my ways is: create two tables first. If you know better way, please let me know.
Table Tag
id keyword
Table C_Tag
id tag_id user_id
Foreign key Tag(id) Reference C_Tag (tag_id)
<?php
$tag=$_POST['tag_name'] //get the tag name
$current_user=$_POST['users_id'];// get the current user id
include 'db_tag.php';
$stmt = $db->prepare("SELECT keyword, id FROM Tag WHERE keyword = :tag ");
$stmt->bindParam(':tag', $tag);
$stmt->execute();
$row_tag = $stmt->fetchALL(PDO::FETCH_ASSOC);
foreach ($row_tag as $row_tag){
}
//if the keyword exist, only update the C_Tag table
if ($row_tag['term'] == $tag){
$stmt = $db->prepare("SELECT t.id, t.keyword, ct.tag_id, ct.user_id FROM Tag t , C_Tag ct WHERE t.id=ct.tag_id ");
$stmt->bindValue(':current_id',$current_user);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
foreach ($row as $row){
}
$row_id=$row['id'];
$row_tag_id=$row['tag_id'];
$row_user_id=$row['user_id'];
if( $current_user == $row_user_id && $row_id == ! $row_tag_id ){
//make sure same user cannot enter duplicate keyword
$stmt = $db->prepare ("INSERT INTO C_Tag (user_id, tag_id)
SELECT :current_id, id
FROM tag
WHERE keyword=:keyword
");
$stmt->bindValue(':current_id',$current_user);
$stmt->bindValue(':keyword', $tag);
$stmt->execute();
}
} else {
//if the keyword is new, I will insert it into both table
}
?>
this appears to be the solution
How to copy a row and insert in same table with a autoincrement field in MySQL?
insert into zr1f4_k2_tags_xref (id, tagID, itemID) select NULL, tagID, #itemID from zr1f4_k2_tags where name=#tagName
but i cant make it work.
this are the tables
zr1f4_k2_tags
id int(11)
name varchar(255)
published smallint(6)
zr1f4_k2_tags_xref
id int(11)
tagID int(11)
itemID int(11)
I'm trying to insert the ID of the tag related to the tagname and item ID which ill add explicitly. and the id is autonumeric

Do i really need an auto increment id column?

I have a table structure with META_ID | KEY | VALUE | USER_ID where META_ID is auto-increment. Now in my php logic
1 get the result key-value pairs per user
2 delete the key value row per user
3 update or insert the key value pair for a already known USER_ID
4 insert key value pair for a new user
But the META_ID keeps growing, so i was wondering if i could just delete the META_ID column?
Case logic
An registered user or returning registered user can update their form over time if they haven't submit it yet. So overtime an user can select and deselect certain form options and update, insert or delete is triggered.
Now the logic behind "returning user deselects a key (and the row needs to be deleted)" gives me a problem. That's why i just delete all users key-value pairs. But what would be the right way?
So if the key-value exists in the db table but not in $params i need to delete it!
btw here's my function
function user_shopping_meta_data($params) {
global $wpdb;
$shopping_meta_table = 'wp_shopping_metavalues';
$wp_user_id = $params['wp_user_id'];
//1 CHECK IF USER HAS KEY VALUE PAIRS
$checkKeyValues = $wpdb->get_results("SELECT meta_shopping_key FROM $shopping_meta_table WHERE wp_user_id = '$wp_user_id'");
//2 WE DELETE
$qdel = $wpdb->delete($shopping_meta_table, array('wp_user_id' => $wp_user_id));
//3 UPDATE OR INSERT
foreach ($params as $key => $val) {
//variables
if (is_array($val)) {
$val = json_encode($val);
}
$shopping_meta_values = array(
'wp_user_id' => $wp_user_id,
'meta_shopping_key' => $key,
'meta_shopping_value' => $val
);
if (count($checkKeyValues) > 0) {//3 USER IS KNOWN SO UPDATE and/or INSERT new key-value
foreach ($checkKeyValues as $check) {
//UPDATE OR INSERT
if (($key != "wp_user_id")) {
//FOR UPDATE where
$shopping_meta_where = array('meta_shopping_key' => $key, 'wp_user_id' => $wp_user_id);
$result = $wpdb->get_results("SELECT * FROM $shopping_meta_table WHERE meta_shopping_key = '" . $key . "' AND wp_user_id = '$wp_user_id'");
if (count($result) > 0) {//KEY ALREADY EXISTS FOR USER
$return .= $wpdb->update($shopping_meta_table, array('meta_shopping_key' => $key, 'meta_shopping_value' => $val), $shopping_meta_where) . '<br/>';
//$return .= 'UDPATE<br/>';
} else {//KEY IS NEW
$return .= $wpdb->insert($shopping_meta_table, $shopping_meta_values) . '<br/>';
// $return .= 'INSERT for old';
}
}//.end $key
}//.end foreach checkKeyValue
}//.end count
else {//4 INSERT KEY VALUE PAIR FOR NEW USER
if (($key != "wp_user_id")) {
$return .= $wpdb->insert($shopping_meta_table, $shopping_meta_values) . '<br/>';
// $return .= 'INSERT NEW';
}
}
}//.end each
echo 'Test return: ' . $return;
}
You won't gain much by deleting it. You might think that you save some space, but in fact you don't. An auto_increment column is always also (part of) the primary key. If you delete it, MySQL will create an "implicit" primary key, which is not visible but necessary for MySQL to identify rows. Also you will lose some comfort like not being able to use LAST_INSERT_ID().
You can very well delete it. It is just a unique ID. If you can distinguish different rows without the META_ID or you do not need to distinguish rows, then META_ID is redundant.
If i can give you a suggest is better to leave that field as a history.
If you need to want to know what is the last action done for that user you can order by META_ID.
Is usefull to have a primary key in a table. But this is just a suggest
I suggest you have a primary key that you are sure of that it is unique. It is a good idea to use a auto-increment column for this because you will always be sure that it is unique.

mysql, if row exists incrament value else insert row without key

I'm trying to do something that may be too complicated for MySQL
If a row exists i'd like it to update a counter and if not insert the row...I did a search and found this...
$query = "insert into TABLE
(`id`, `item`, `count`, `option1`, `option2`)
values
('$cartName', '$sku', 1, '$option1', '$option2')
on duplicate key
update count = count + 1";
but I don't have a key in the table so the "on duplicate key" won't work, the query needs multiple ANDs to check the row based on the id, item, and 2 option values.
an added thing is to have mySQL return a count of all count values based on the item
This is what I have currently (modified from search :), does anyone know how to reduce this into a single query?
option1 and option2 are variable and could be null so that's why the 2 if statements and is called from AJAX so the $message is used to update the javascript client side.
$query = "update TABLENAME set count=count+1 where item='$item'";
if($option1) $query .= " AND option1='$option1'";
if($option2) $query .= " AND option2='$option2'";
$result = mysql_query($query) or die("Error:".mysql_error() );
if (mysql_affected_rows()==0) {
$query = "insert into $table11 (`id`, `item`, `count`, `option1`, `option2`) values ('$id', '$item', 1, '$option1', '$option2');";
$result = mysql_query($query) or die("Error:".mysql_error() );
}
//total count for all items with specific id
$query = "SELECT SUM(count) FROM TABLENAME WHERE id='$cartName'";
$result = mysql_fetch_row(mysql_query($query)) or die("Error:".mysql_error() );
$message = $result[0];