SQLite 3 , duplicate a row and change only one field - php

I have some table in my SQLite3 database , for example
table1
table2
table3
All tables have a field called id (integer NOT NULL PRIMARY KEY UNIQUE) (not auto increment)
My goal is to duplicate a record of one of these tables, changing only the id field (with a new id). I would like to do this without having to know the name of all the columns in each table.
I tried this solution, it works, but in this way i have to know the names of all columns
INSERT INTO table1 (id,column1,column2,column3)
SELECT NEWID,column1,column2,column3 FROM table1
WHERE id = OLDID
I tried also the method to create a temporary table, but without success
I have to run a query like this PRAGMA table_info(table1) , save the columns's name in an array , and then run a query created with a cycle ?
thanks
My solution
$TABLENAME = "mytablename";
$ID = 1423659222480;
$NEWID = 1423659222481;
$db = new PDO('sqlite:db.sqlite3');
$result_columns = $db->query("PRAGMA table_info(".$TABLENAME.")");
$appColumns = array();
$appColumns2 = array();
foreach ($result_columns as $row) {
array_push($appColumns, $row["name"]);
if($row["name"] != "id") array_push($appColumns2, $row["name"]);
}
$appColumns = implode(",",$appColumns);
$appColumns2 = implode(",",$appColumns2);
$appColumnsWithoutID = $NEWID.",".$appColumns2;
$queryDuplicate = "INSERT INTO ".$TABLENAME." (".$appColumns.") SELECT ".$appColumnsWithoutID." FROM ".$TABLENAME." WHERE id = ".$ID;

Related

INSERT / UPDATE Mysql Single Form

I have 2 database tables
tbl1 users ---------- tbl2 gamesystems
uid field ------------- gs_uid field
the 2 tables are tied together by the user_id..
now i want tbl2 to only be updated able and fields are not required.. with the exception of the gs_uid when they update there system.
my only issue is i need to insert the user_id into the gs_uid.
function game_system()
{
if(isset($_POST['game_system'])) {
$user_id = $_SESSION['uid'];
$motherboard = escape($_POST['motherboard']);
$processor = escape($_POST['processor']);
$memory = escape($_POST['memory']);
$graphics = escape($_POST['graphics']);
$harddrive = escape($_POST['harddrive']);
$power = escape($_POST['powersupply']);
$cooling = escape($_POST['cooling']);
$towercase = escape($_POST['towercase']);
$sql = "INSERT INTO gamesystem(gs_uid, motherboard, processor, memory, graphics, harddrive, powersupply, cooling, towercase) ";
$sql .= "VALUES('{$user_id}','{$motherboard}','{$processor}','{$memory}','{$graphics}','{$harddrive}','{$power}','{$cooling}','{$towercase}') ";
$result = query($sql);
}
}
If gs_uid is the primary key of table 'gamesystem' , then this field should not accept empty data.
Otherwise, if gs_uid is NOT the key, what's the primary key of this table? In case of UPDATE, you'll need to specify which row you'd like to update, otherwise the system will not know how to do so.
the SQL should looks like below
UPDATE "gamesystem"
SET "gs_uid" = $user_id
WHERE YOUR_PRIMARY_KEY_COLUMN = SPECIFIC VALUE;

How to alter a table (add a column) simultaneously when a row is added (column name = row id) in another table?

How to write code in MySQL such that when ever a row with a primary key id is added to a table, a corresponding column is added in another table such that the name of the column is equal to the id of the row just added.
I tried the following but to no use.
sqlQuery("INSERT INTO table1(name) VALUES('$name')");
$id = sqlQuery("SELECT id FROM table1 WHERE id = LAST_INSERT_ID()");
$id = mysqli_fetch_array($id);
$id = $id['id'];
sqlQuery("ALTER TABLE table2 ADD '$id' INT(2) NOT NULL");
sqlQuery - user defined function that return mysqli_query result.
Any help would be great.
Also, I'm a newbie. Sorry if this is a silly question to ask.
Make it OOP style and there is a var in the class that automatically returns the last updated item.
$con = new mysqli(SQL_HOST, SQL_USER, SQL_PASSWORD, SQL_DATABASE); //do normal error checking with database connection
$sql = "INSERT INTO table1(name) VALUES('$name')";
$con->query($sql);
$sql2 = "ALTER TABLE table2 ADD '$con->insert_id' INT(2) NOT NULL" //$con->insert_id is the parm you are looking for.
$con->query($sql2);

PDO insert into table with foreign keys

I am having a few difficulties with mysql and PDO.
I wish to insert a product into the database, however the product table contains foreign keys. Naturally, I will not know the Foreign key ID when inserting. Am I doing this right??? Is there a better way of tackling this problem?
TABLE Products
Id PK AI int
Name Varchar(20)
CategoryId Int FK
TypeId Int FK
TABLE Categories
Id Int PK
Cat varchar(20)
TABLE Types
Id Int PK
Type varchar(20)
$type = 'Gloves';
$category = 'Clothing';
$sql = 'INSERT INTO Products
SET Name = :name, CategoryId = :catId, TypeId = :typeId
WHERE
CategoryId IN (SELECT Id FROM Categories WHERE Cat = :category) AND
TypeId IN (SELECT Id FROM Types WHERE Type = :type)'
$stmt = $db->prepare($sql);
$stmt->execute(array(':name' => 'Pink childrens gloves', ':category' => $category, ':type' => $type));
As mentioned in a comment below: Normally, I would be getting the ID from a select box. I cannot do this because it will be a script executing the query, not a user.
are you sure that this is what you want?
$sql = 'INSERT INTO Products
SET Name = :name
WHERE
CategoryId IN (SELECT Id FROM Categories WHERE Cat = :category) AND
TypeId IN (SELECT Id FROM Types WHERE Type = :type)'
I think you are trying to use UPDATE
$sql = 'UPDATE Products
SET Name = :name
WHERE
CategoryId IN (SELECT Id FROM Categories WHERE Cat = :category) AND
TypeId IN (SELECT Id FROM Types WHERE Type = :type)'
MySQL allows a combination of SELECT + INSERT in a single query:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
... but I wouldn't care about it. You cannot do proper error checking if you do three different things in a single query.
My advice is that you first validate that there're a category and a type that match the given names. In that step, you can easily get the corresponding IDs, which will let you perform a simple INSERT. Additionally, if you need to insert many products, you can validate first and once.
In addition to #Álvaro G. Vicario's answer, you can also do something like (works in normal sql, I have not tried it with bound variables):
$sql = 'INSERT INTO Products
SET Name = :name,
CategoryId = (SELECT Id FROM Categories WHERE Cat = :category),
TypeId = (SELECT Id FROM Types WHERE Type = :type)';
But I would always check for existing categories and types first, insert where necessary and get the required id's as this will lead to unexpected results if there are no matches in the inner selects.
First of all you need to figure out which is the table that have foreign key data.
Then you need to get all possible values from foreign key table.
Finally you need to build and drop-down list or similar to give ability of select acceptable foreign key.
$q=$db->prepare('SELECT ke.referenced_table_name assoc_table,
ke.referenced_column_name assoc_col FROM
information_schema.KEY_COLUMN_USAGE ke WHERE ke.referenced_table_name IS NOT NULL
AND ke.table_schema=:database AND ke.table_name=:tablename AND ke.column_name=:col');
$q->bindValue(':database','mydatabasename'); //Set your database name here
$q->bindValue(':tablename','Departments'); //Set your table name here
$q->bindValue(':col','City'); //Set the column which foreign key values you want to have here
if($q->execute()) {
$foreingtable=$q->fetch(PDO::FETCH_ASSOC);
$q=$db->prepare('SELECT '.$foreingtable['assoc_col'].' FROM '.$foreingtable['assoc_table']);
if($q->execute())
echo json_encode($q->fetchAll(PDO::FETCH_COLUMN));
}
else {
header('http/1.1 500 Internal Server Error');
print_r($q->errorInfo());
exit;
}
More about this: Get list of possible foreign key values in MySql using PDO

insert data from one table to another table

I am having a problem locating comments for a given user with the following table structure:
usertable (id, userid, name)
comments (id, commentname, date)
Note: usertable.id is not the same as comments.id, and they are both autoincrement
How should I go about updating these tables to fix this problem?
Update
Is this code good for all users get their own votes when someone voted as thilo savage told me ?
$sth = thumbsup::db()->prepare(
'INSERT INTO'
.thumbsup::config('database_table_prefix')
.'votes_users(vid, userid) VALUES (?,?)');
$sth->execute(array($this->vid, $userid));
You've got two options:
Add a 'uid' column to the comments table which references the usertable's 'id' column. That way, you have a way to keep track of which comments belong to which users.
Create a table 'user_comment' with the columns 'uid' and 'cid'. This option leaves the two existing tables as they are, and the 'user_comment' table is responsible for keeping track of which comments belong to which users.
EDIT: Rewritten to use many-to-many relationship because current tables can't be altered.
Create a new table called comments_users with these fields:
cuid (primary key and auto increment) | cid | uid
Then get all of a user's comments with this code:
$user_id = '1234';
// get all the user's comment ids from comments_users table
$find = mysql_query("SELECT `cid` FROM `comments_users` WHERE `uid` = '".$user_id."'");
// generate a query that grabs all those comments
$load = "SELECT * FROM `comments` WHERE ";
while ($row = mysql_fetch_array($find) {
$load .= "`id` = '".$row['cid']."' OR ";
}
// shop off the last OR
$load = substr($load,0,-4);
// put all the user's comments into comments array
$q = mysql_query($load);
while ($comment = mysql_fetch_array($q)) {
$comments[] = $comment
}
print_r($comments);
As far as inserting goes, you'll insert comments into the comments table like you normally would, but then you'd ALSO insert a row into comments_users table filling in the appropriate cid and uid for that comment

Add Prefix to auto-increment in mysql db

I have my database with table test1.
It has a primary id "Id" which is auto-increment.
Now the id is in the format 1,2,3.. . .Is it possible to store the primary Id as
PNR1,PNR2,PNR3 .. . . and so on(with auto-increment).
No. Either add the prefix in the query, or use a view instead.
Not really, but you can use another column (but a view)
this is already covered here:
MySQL Auto Increment Custom Values
Yes you can do it if you have INT prefix. You have id as INT in table
// START PREFIX
$query = mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 1");
// GET THE LAST ID MAKE SURE IN TABLE YOU 9991
while ($row = mysql_fetch_object($query)) {
$lastId = $row->id;
}
list($prefix,$Id) = explode('999',$lastId );
$Id = ($Id+1);
$new_id = '999'.$Id;
// END PREFIX
$insertQuery = mysql_query("INSERT INTO `table_name` SET id = '".$new_id."',...");
Hi, I made it work in this way :
Products Table (products):
id_prod(varchar(11), NOT NULL, PK), name(varchar(40))
Products Sequence Table (productidseq):
id(AI, PK, NOT NULL)
Before Insert Trigger in Products Table:
CREATE DEFINER=`root`#`localhost` TRIGGER `dbname`.`products_BEFORE_INSERT` BEFORE INSERT ON `products` FOR EACH ROW
BEGIN
insert into productidseq (id) values(NULL);
set new.id_prod = concat('PROD or any prefix here',last_insert_id());
set #productId = new.id_prod; -- To use outside of trigger this variable is useful.
END
When you run below query :
insert into products (name) values('Bat');
data inside tables will we be like this :
products:
id | name
---|-----
1 | Bat
productidseq:
id
---
1
If any better way than this or any cons with this, please comment below. Thanks.

Categories