how do I update mysqli column names dynamically - php

I have 10 columns in a mysql database that I would like to call with a function. The names of the columns are;
videoSec1,
videoSec2,
videoSec3,
videoSec4,
etc. Can the statement be set with a variable? The example that I came up with is not working.
$stmt1 = $mysqli->prepare('UPDATE users SET ("videoSec"+index)=? WHERE userID=?);
$stmt1->bind_param('ii',$secc,$userID);
$stmt1->execute();

You have to create another table videoSec, consists of 2 columns: index and userID
And instead of updating it, just add or remove rows:
$stmt = $mysqli->prepare('INSERT INTO videoSec SET index=?, userID=?');
$stmt->bind_param('ii',$secc,$userID);
$stmt->execute();
this is how relational database works.

Related

Moving records to a new table updating original id accordingly

I need to create a new table with certain data from another table but update the original table with the ID of the newly inserted record from the new table. Like so:
NEW_TABLE
----------------
id
-- other data --
ORIGINAL_TABLE
----------------
id
new_table_id
-- other data --
However, the added records to new_table will be grouped to get rid of duplicates. So, it won't be a 1-to-1 insert. The query needs to update matching records, not just the copied record.
Can I do this in one query? I've tried doing a separate UPDATE on original_table but it's not working.
Any suggestions?
You are going to be doing 3 seperate queries as I see it.
$db = new PDO("...");
$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();
$results = $stmt->fetchAll();just iterate o
foreach ($results as $result) {
$stmt = "INSERT INTO new_table (...) VALUES (...)";
$stmt = $pdo->prepare($stmt);
$data = $stmt->execute();
$insert_id = $pdo->lastInsertId();
// Update first table
$stmt = "UPDATE table SET id=:last WHERE id=:id";
$stmt = $pdo->prepare($stmt);
$data = $stmt->execute(array('last' => $insert_id, 'id' => $result['id']));
}
The above is a global example of your workflow.
You can use temporary tables or create a view for NEW_TABLE.
Temporary Tables
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.
--Temporary Table
create temporary table NEW_TABLE as (select * from ORIGINAL_TABLE group by id);
Views
Views (including updatable views) are available in MySQL Server 5.0. Views are stored queries that when invoked produce a result set. A view acts as a virtual table. Views are available in binary releases from 5.0.1 and up.
--View
create view NEW_TABLE as select * from ORIGINAL_TABLE group by id;
The view will always be updated with the values in ORIGINAL_TABLE and you will not have to worry about having duplicate information in your database.
If you do not want to use the view, I believe you can only perform an insert on one table at a time unless you have some sort of view that would allow you to do both, but you probably want to do it as two steps in a transaction
First you will have to tell the database that you want to start a transaction. Then you will perform your operations and check to see if they were successful. You can get the id of last inserted row (this assumes you have an auto_increment field) to use in the second statement. If both statement seem to work fine, you can commit the changes, or if not, rollback the changes.
Example:
//Assume it will be okay
$success = true;
//Start the transaction (assuming you have a database handle)
$dbh->beginTransaction();
//First Query
$stmt = "Insert into ....";
$sth = $dbh->prepare($stmt);
//See if it works
if (!$sth->execute())
$success = false;
$last_id = $dbh->lastInsertId();
//Second Query
$stmt = "Insert into .... (:ID ....)";
$sth = $dbh->prepare($stmt);
$sth->bindValue(":ID", $last_id);
//See if it works
if (!$sth->execute())
$success = false;
//If all is good, commit, otherwise, rollback
if ($success)
$dbh->commit();
else
$dbh->rollBack();

Issue with copying from one MySQL table to another

I'm trying to copy from one table to another table and it works fine, however I also need to insert the current user ID in the new table. I haven't yet figured out how. Normally I would do something like SET user_id = :user_id, but i have never worked with this one.
This is my code:
$q = $conn->prepare("INSERT INTO user_themes(title,code_entry,code_home,code_css,code_category,code_archive)
SELECT title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");
So my question is:
How can I insert user_id (let's say user_id is 1) into the new table as well?
The basis of your query doesn't change. Just add the value to both the columns and `SELECT statement:
INSERT INTO user_themes(user_id, title,code_entry,code_home,code_css,code_category,code_archive)
SELECT :user_id, title, code_entry, code_home, code_css, code_category, code_archive
FROM blogy_themes WHERE id = :id
Then when you execute, bind both :id and :user_id.
From what I understand you want to have the id of the user that is doing the action in all of the new records, you can do something like:
$q = $conn->prepare("INSERT INTO user_themes(user_id,title,code_entry,code_home,code_css,code_category,code_archive)
SELECT '" . (int) $userid ."' as user_id, title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");
This is a workaround in order to keep using the query as it is.
Second option is more "ORM" approach, you can query all the relevant records from the user_themes table, iterate on the result set, clone each row and save it with new user_id.

PDO insert new record to database based on lastInsertId()

Ive just started learning PDO and I'm struggling by simply inserting a new record based from
$lastid = $db->lastInsertId();
The ID gets created in the database table from another function.
But nothing happens when i try to insert a new record based on that ID.
function add_name($last_id, $name) {
$db = some_db();
$query = "INSERT INTO team (name) VALUES (:name) WHERE id = '".$last_id."'";
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
}
INSERT ... WHERE is not valid SQL. If you are inserting a new record, an autoincremnt ID will be generated at that time (if you have such defined for the table).
If you are trying to INSERT a new row into a related table with the last id from another table, then you would set that value as one of your column inputs. So the workflow would look like this:
INSERT [column data for table_a] INTO table_a
[GET autoincrement from last insert]
INSERT (table_a_foreign_key_column, [other table_b columns]) VALUES (table_a_id, [other table_b values) INTO table_b
UPDATE:
Since UPDATE is what you want, you can make update like this:
UPDATE team
SET name = :name
WHERE id = :id
You should use parameters for both name and id values. It is still not clear to me why you would need to make an insert and then an update within the same script execution. It's not like you received any more input from the user that you did not already have. I would guess you could just insert this name values when first creating the record and save yourself the extra trouble of multiple queries.
i think your sql query is wrong, try this:
function add_name($last_id, $name) {
$db = some_db();
$query = 'INSERT INTO team (id, name) VALUES (:id, :name)';
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt ->bindParam(':id', $last_id, PDO::PARAM_INT);
$stmt->execute();
}
MySQL Insert Where query

PHP MYSQLi - Backup column data (into another table/column) before updating column

I am working on a system which keeps track of what was in the field, prior to it being updated. I'd prefer using a table for the previous data, but am open to other options. This is some sample code which would accomplish the task :
<?php
$initial_value = $_POST['some_value'];
$id =231212213; // some id
$stmt = $mysqli->prepare("SELECT column FROM table WHERE user=?")
$stmt->bindParam("s", $id);
$stmt->execute();
$stmt->bind_result($column);
$stmt->fetch();
if ($column !="") {
//edit : it doesnt matter to me whether the data is moved into a new table or column
$stmtA = $mysqli->prepare("UPDATE another_table SET backup_column=? WHERE user=?");
$stmtA->bindParam("ss", $column, $id);
$stmtA->execute();
$stmtB = $mysqli->prepare("UPDATE table SET column=? WHERE user=?");
$stmtB->bindParam("ss", $initial_value, $id);
$stmtB->execute();
}
?>
This is a pure mysql commands solution which you could modify your code to do:
1.) CREATE TABLE new_table_name LIKE old_table_name
2.) INSERT INTO new_table_name SELECT * FROM old_table_name
Done. ;-)
This way you have an exact backup of your table previously, and joins are very easy to see the differences:
SELECT a.*, b.* FROM old_table a JOIN new_table b ON a.id=b.id WHERE <criteria>;
EDIT
UPDATE BACKUP SET COLUMN = (SELECT COLUMN FROM TABLE WHERE user_id=#) WHERE user_id=#;

How do I get all the ids of the row created by one multiple row insert statement

I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?

Categories