Php - alter table column after insert - php

is it possible adding a column into a database table after an insert?
If yes kindly give me an example code for it i don't know how to make of it

yes it is possible for example :
CREATE TABLE my_table (
id integer(10),
fname varchar(50) );
and insert the values :
INSERT INTO `my_table`(`id`, `fname`) VALUES (1,'edverd');
see the value is added here
NOW Alter the Table
ALTER TABLE my_table ADD COLUMN lname varchar(50);
see the table is altered here
but the values in the added column will be null for every row present in that table.
now you can simply add the values in the added column
INSERT INTO `my_table`( `lname`) VALUES ('cullen');

To Answer Your Question:
Yes you totally can.Just an FYI
Insert Is basically Creating a Brand New row.(If there is something already present in the row You use UPDATE)
to add Column to the database the syntax remains the same, if you are using mysql this is something your code should look like
$query="ALTER TABLE Users ADD COLUMN PASSWORD VARCHAR(100)";
$result= $mysqli->query($query);
if(!$result) echo "Failed to Add column TO The database";
BUT:
1.What you are trying to do isn't a good practice.
2.Read More about Php, You can get a course on udemy or just buy books on Php one of which is Learning PHP MYsql and Javascript By Robin Nixon, or just read more from the php manual, or mysql manual.
3.Nobody is Rude here, but lack of effort is something nobody appreciates.
4.Lastly don't get disheartened,Work Hard

Related

How do I insert a piece of information to an already existing record?

I have an SQL Database setup with rows of data already there. How do I update just one column of one row by grabbing the id (appointmentspage.php?id=1")?
I already have written the code to input the data into the correct position table I want, but I am having trouble selecting the id too
if(isset($_POST["submit"]))
try{
$sql = "INSERT INTO appointments (Notes)
VALUES ('".$_POST["Notes"]."')";
I feel like = $_GET['id']; or WHERE appointments.ApptID = :id should be used, but I can't fathom it.
Currently the 'Notes' column in my SQL table gets an input, but it creates a new empty row with only that data added. I want to select an existing row/entry and add the Notes to that.
On my site I have a set of examples for the basic use cases, you are welcome to check them out.
Your case would be UPDATE query using PDO.
First of all, "insert into an existing record" is called UPDATE. You need to check out your SQL textbook.
And yes, you need something like ApptID = :id in your query. However personally I prefer simple ? marks
So it should be something like
$sql = "UPDATE appointments SET notes=? WHERE ApptID=?";
$stmt= $dpo->prepare($sql);
$stmt->execute([$notes, $id]);
Note three shouldn't be any try or catch stuff around.
You need to define ApptID field as Primary Key with auto-increment field in database define. In MySQL, a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
After that you can use that ApptID for update your existing data using Update query in MySQL

SQL Auto Increment ID

I have an SQL table with an auto-increment field. I know people have asked how to retrieve the ID of the 'last entry' after the insert has taken place, and I know how to do that. What I want to do is duplicate the auto-generated field in to a second column of the same table - how do I modify my insert code to do this:
mysql_query("INSERT INTO `tags` (`tid`,`tagid`,`tagname`) VALUES('','INSERTED.ID','{$tagname}')");
The reason I want to do this is because I want to be able to make two rows equal each other. I.E. if two different tags (with different unique ids) have the same tagid, then I can use the 'tagid' reference elsewhere as a unique identifier and cycle through them. I can also retain knowledge of which tag is the parent tag - because it will have the same 'tid' as 'tagid'.
I have a system for tagging events; but sometimes I miss-spell a tag... so rather than correcting all the mistakes, I want to make my system error proof by allowing miss-spelt tags to be joined up and treated the same way as a the correct tag.
Would appreciate your help - even if that means doing this a completely different way.
Thanks,
2 options:
1) You can use LAST_INSERT_ID() mysql function, but in a second query, not in the same.
SELECT LAST_INSERT_ID();
2) Define a insert Trigger in the table, then when you insert, the trigger "triggers" and do the action in the trigger.
CREATE TRIGGER tag_tid BEFORE INSERT ON tags
FOR EACH ROW NEW.tid = NEW.id;
Note: Short creator, see more in the link.
you have to alter the table to set the field to autoincrement. And then I believe when you insert anything it increments. There is also this statement called on duplicate...http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You could store the previous id, and then use it in your query string.
$previous_id = mysql_insert_id();
mysql_query("INSERT INTO `tags` (`tid`,`tagid`,`tagname`) VALUES('','$previous_id','{$tagname}')");

Updating a MySQL table

I need on coding to check a mysql DB to see if it needs to be updated. The DB is for stock info & will only download the info if it is not currently in the DB. I'm trying to figure how to design my code without making some long peice of coding that may be able to be done in a few lines of code.
I currently am using the information_schema UPDATE_TIME info for the table, so I have that info. But where I'm stuck is how to I use php to check if the DB needs to be updated.
So in essence, I'm looking for a code snippet that will check to see if the table needs to be updated but will check for the duplicate info (i.e. if it makes it through an "if" statement & then downloads it anyway, if it is duplicate info, it will not insert it [I can use the date for this]).
Thanks
Think of this :
$result = mysql_query("SELECT * FROM tableName" WHERE ConditionYouHave)
or die(mysql_query("INSERT INTO tableName VALUES ('value1','value2','value3')"));
Do you have some sort of datafeed you can run through to check for new data? If this is the case I would go line-by-line through the file looking for new rows. When you find one, you insert it into your table. If the row already exists just continue on to the next row. This can be done fairly simply in PHP.
INSERT INTO table_name (id, column2)
SELECT {$int_id}, '{$str_column2}'
FROM table_name
WHERE id = {$int_id} AND column2 != 'what ever you want'
ON DUPLICATE KEY UPDATE column2 = VALUES(column2)
table_name is your own table's name.
I assumed you have a id column. And column2 is just an example.
You can validate your row through the WHERE and have whatever condition you wish.
Your question's comment links to this example.

(mysql, php) How to get auto_increment field value before inserting data?

I'm uploading image file to storage server. Before uploading I should compose filename, which contains AUTOINCREMENT VALUE in it (for example, 12345_filename.jpg).
How could I get autoincrement value before inserting into DB?
I see only one solution
insert empty row
get it's autoincrement value
delete this row
insert row with real data using autoincrement value from p.1
Is there any other solutions?
Thank you
The autoincrement value is generated by the database itself, when the insertion is done ; which means you cannot get it before doing the actual insert query.
The solution you proposed is not the one that's often used -- which would be :
insert some half-empty data
get the autoincrement value that's been generated
do your calculations, using that autoincrement value
update the row to put the new / full data in place -- using the autoincrement generated earlier in the where clause of the update query, to identify which row is being updated.
Of course, as a security precaution, all these operations have to be made in a transaction (to ensure a "all or nothing" behavior)
As pseudo-code :
begin transaction
insert into your table (half empty values);
$id = get last autoincrement id
do calculations
update set data = full data where id = $id
commit transaction
well, try this:
$query = "SHOW TABLE STATUS LIKE 'tablename'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
var_dump($row);
output:
array(18) {
[...]
["Auto_increment"]=> string(4) "3847"
[...]
}
This will be your next auto_increment ID.
If you are using PDO, here is a "single line" solution :
$nextId = $db->query("SHOW TABLE STATUS LIKE 'tablename'")->fetch(PDO::FETCH_ASSOC)['Auto_increment'];
where tablename is replaced by your table.
There is no solution. You get the auto-increment value when you insert a new row, full stop. Inserting and deleting won't help, since the next auto-increment value will be one higher. Do to possibly multiple clients talking to the database at the same time, you can't predict the next value since it might be incremented between your guessing and your actual insert.
Find a different solution. Either insert a row and update it later, or generate an id for the filename that's independent of the auto-increment id.
#Pascal Martin makes a good point. In cases like this, I personally like to add another ID column, containing a random, 16-digit ID (which will also be the "public" ID in web apps and on web sites for security reasons). This random ID you can set beforehand in your application, work with it, and then set when the record is actually created.
Use a separate table just as a counter, like a postgresql sequence, and don't use auto_increment in your main table(s).
INSERT INTO CONTACTS1 (firstname, lastname) values('hi', select auto_increment from information_schema.TABLES where TABLE_NAME='CONTACTS1' and TABLE_SCHEMA='test')
Where ID is the Primary Key & Auto number column.
Well this is to old ,but if someone else need it.
You can get this kind of value at "information_schema" table where you could do something like
select AUTO_INCREMENT from TABLES where TABLE_SCHEMA = 'You're Database' and TABLE_NAME = 'Table Name'
So this kind of Meta Data are always stored in Information_schema .

Alter MySQL column with values to auto increment

I had a hard time with the title, so let me explain.
What I'm doing is using the jQuery UI to create sortable list elements on a page. Once the order is submitted, php assigns an incrementing value to the list elements based on their order, drops the existing id column, creates a new id column and inserts each list elements value WHERE title=x. This creates the proper order of ID's, and is working fine.
What I'd like to do now is change the column to auto_increment, such that if I insert a new entry, the id is assigned automatically, one number higher than the greatest number generated by the php script. I'm not using any foreign keys or anything, just this simple table.
Is this possible?
My mistake, I misread your question. You do not want to use the database itself to provide numbering based on your sort order. You can however use the SQL query itself to return an incrementing field. One sec and I'll update with that info...
Ok, here it is:
you need to use a variable like
set #n=0;SELECT
#n:=#n+1 as 'n',
col1,
col2
from table
However, i highly recommend you just create the numbering in your php code if at all possible.
----------------Original Post----------------
This is pretty easy with phpmyadmin. Let me know if your unable to install that and I'll dig up the necessary SQL.
All heck, here is the SQL:
alter table t1 modify f1 int(4) auto_increment
alter TABLE tbl auto_increment = xxx; //change xxx to be the next id it should use
you may need to run these in opposite order depending on your existing data set it will fail to add auto_increment if you don't change the value of auto_increment to be something not already in use.

Categories