I have a few nagging questions about creating tables:
If I use PHP to create a MySQL function to create a table, I know it works the first time (to create a database for usernames and passwords) but what about the following times when the database sees the code to "create table". It seems to ignore it on my virtual server, but I was just wondering if this is wrong. Does it keep trying to create a new table each time? Is it okay to leave that code in?
Another question I have is, let's say I go into PHPMyAdmin and add a column called "role" (to define the user's role). The sign in page will crash since I added a column in PHPMyAdmin, but if add the column using PHP/MySQL it is perfectly fine. Why is that?
CREATE TABLE is executed each time you run the function. It's better to replace the syntax with CREATE TABLE IF NOT EXISTS.
The keywords IF NOT EXISTS prevent an error from occurring if the
table exists.
If you does not add IF NOT EXISTS it will throw the error.
Reference: http://dev.mysql.com/doc/refman/5.7/en/create-table.html
Please post your code in question to help you with second query.
1.) It depends on the purpose of the table.
If you need to create tables dynamically then your code should check each time
if the table exists:
CREATE TABLE IF NOT EXISTS 'yourTable'
However if you create the table only ones, there is no need to check for existence over and over again, so the code to create these table(s) should execute one time only.
2.) You need to update the function that does the insert or read after adding a column via PHPMyAdmin. It's difficult to answer your second question as I don't know what your functions do.
Do not keep your CREATE TABLE ... statements in your PHP code so that they execute every single time on every single page load. It's unnecessary and error prone. The statements are not being ignored, very likely they are run and are producing errors, and you're simply not checking for errors.
Database creation is a deployment step, meaning when you upload your code to your server, that's the one and only time when you create or modify databases. There are entire toolchains available around managing this process; learn something about automated deployment processes and database schema versioning at some point.
No idea without seeing your code and the exact error message.
Related
I was looking into using a database to store a generated link to that database entry that holds more information about the database entry. So you would see a bit of the database, then click on the entry and open a new page that holds more information about that entry.
What I was looking for was something to keep track of the amount of entries that have been entered, even if one of the entries have been removed. I know SQlite3 has count, but I haven't seen anything that would keep track of this. I was thinking in order reach my goal I would have to just set a counter and write it to a file and pull that counter when I am making a new entry, just wondering if anyone know something else I can do instead of reading/writing a file for one number.
Should be noted this is on a server that can be shutdown and restarted, the user must enter in the information that goes into the database and the server will log it for the user. And I don't want to every repeat the same entry number.
I have mainly used PHP, HTML, and Python for the current project I am working on.
I looked into this out of curiosity because you can do 'post save' and 'pre save' in most ORM-based webapps.
"A trigger may be specified to fire whenever a DELETE, INSERT, or UPDATE of a particular database table occurs"
https://sqlite.org/lang_createtrigger.html
CREATE TRIGGER aft_insert AFTER INSERT ON emp_details
BEGIN
INSERT INTO emp_log(emp_id,salary,edittime)
VALUES(NEW.employee_id,NEW.salary,current_date);
END;
It seems like the answer I was looking for was built into SQLite3, which is the best kind of answer.Auto Increment in SQlite3 allows for me to do what I was looking for. It will keep track of the amount of entries that have been added meaning I will be able to generate a link from the ROWID that I set to Auto Increment and not have a chance to repeat that it again.
I would like to back up one of my database tables, abc using PHP.
One of the column is timestamp. I would like to back up the table that is 3 months old into filename.sql.gz and delete the data from the table. Keep latest 3 months data on the table.
If possible the output file only has the INSERT query.
You first need to go through the PHP+database integration tutorials. You can achieve above in mysql query itself. You can use PHP as well...you have to write your own code for this simple task. following are the steps that I will follow in completing this tasks, you can modify the steps according to your requirements...
you have not mentioned which database you are using, am assuming its Mysql/mariadb
Connect database (proper access required), some PHP file management knowledge also necessary
Based on timestamp, you should write a query which can pull the old data and write it to a .sql file (plenty of questions have already been asked on this topic in stackoverflow)
On success of STEP 2, you can perform DELETE operation
While doing this activity, make sure that no other process/queries are running on this database/table.
Script must include TRANSACTION START/BEGIN, COMMIT and ROLLBACK
If you want output file in INSERT query then BATCH INSERT is required. Refer this to get an idea how batch query looks like (How to do a batch insert in MySQL)
You can write a custom PHP function to generate BATCH implementation.
No need to touch the data that you want to keep, will remain as it is
Basically, I am trying to create an interface that will tell an administrator "Hey, we ran this query, and we weren't so sure about it, so if it broke things click here to undo it".
The easiest way I can think to do this is to somehow figure out what tables and cells an identified "risky" query writes to, and store this data along with some bookkeeping data in a "backups" table, so that if necessary the fields can be repopulated with their original contents.
How do I go about figuring out which fields get overwritten by a particular (possibly complicated) mysql command?
Edit: "risky" in terms of completing successfully but doing unwanted things, not in terms of throwing an error or failing and leaving the system in an inconsistent state.
I suggest the following things:
- add an AFTER UPDATE trigger to every table you want to monitor
- create a copy of every table (example: [yourtable]_backup) you want to monitor
- in all AFTER UPDATE triggers, add code: INSERT INTO yourtable_backup VALUES(OLD.field1, OLD.field2..., OLD.fieldN)
How it works: the AFTER UPDATE trigger detects an update of the table, and backups the old values into the backup table
Important: you need to use INNODB table format for triggers to work. Triggers don't work with MyISAM tables.
You may add a timestamp field to the backup tables to know when each row was inserted.
Documentation: http://dev.mysql.com/doc/refman/5.5/en/create-trigger.html
I have a mysql database. What I'd like to do is perform an arbitrary action on it, and then figure out what changed. Something like this:
//assume connection to db already established
before();//saves db state
perform_action();//does stuff to db
diff();//prints what happened
I'd want it to output something like:
Row added in table_0 ]details]
Row added in table_1 [details]
Row modified in table_5 [details]
Row deleted in table_2 [details]
Any ideas?
To further clarify: You know how on stackoverflow, if you check a post's edits, you can see red lines/green highlights indicating what's been changed? I want something like that, but for mysql databases.
Instead of copying your whole database in order to save the state for a later diff, you might be better off by using triggers:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
When you setup appropriate triggers, you can log changes to a table - for example, you can setup a trigger that automatically logs the old values and the new values for every update. To see the changes, query the table that was filled by the trigger.
Of course, the trigger is not restricted to changes made by your application, it will also log updates done by other applications. But this is also the case if you diff the old version of the database with the new version of the database.
I think normally your application would log any interesting changes as it makes them. Or you would set up history tables for everything with datetimes.
To do it the way you describe, you could dump the contents of the database into a file before and after your action and do a diff on the two files. In php, you can check out xdiff: http://us.php.net/manual/en/book.xdiff.php
If this is something you're doing only occasionally in controlled circumstances to test some queries you're not sure about, you can dump and diff on the command line.
One way is to parse the log files, which will give you exact SQL statements executed in your database. I'm not exactly sure how to separate SQL statements made by your application from other applications (if thats the case)
The only thing I can think of is to do some combination of a few somewhat hackey things:
Save a [temporary?] table of row IDs, to check for new rows. If you need to know what was in deleted or modified rows before, you'll need to copy the whole DB, which would be rather messy.
Have each row have a datestamp that gets modified on update; grab rows for whom the updated datestamp is newer than when the analysis started.
Have a layer between your application and the database (if you have something like the classic $db->query(), it would make this easy), log queries sent, which can then be looked at.
I suppose the real question is if you want to know what queries are being executed against the DB, or if you want to know what they queries you're running are actually doing.
I am wondering if it is possible to automate or by button press to move mysql table information from one table to another table deleting it from the first table and putting it in another table? Using php.
My mysql table is big and the page that adds the information to that table has 70 query's on it which slows the page refresh times. I need to move information from the first table to the second at a certain time of day everyday so that those querys don't have to look through all of my giant 27k row table.
Is this possible?
Also if someone could help me with my comment on this page I would be grateful.
link text
PHP doesn't have a constantly running server you can schedule background tasks with.
If you have access to the server you can set up a cron job (or scheduled task under windows) to run the PHP script for you.
Or (and this isnt so nice) you can put the script on the webserver and call it manually at the appropriate time by entering the URL in your browser.
A 27k row table is small by SQL standards, as long as it is properly indexed.
For instance, if you don't care about data from yesterday, you can add an indexed date column and filter with WHERE myDate > NOW() - INTERVAL 1 DAY, and SQL will automatically restrict the query to the rows younger than 24 hours.
I am wondering if it is possible to automate or by button press to move mysql table information from one table to another table deleting it from the first table and putting it in another table? Using php.
You can initiate it from PHP, but what you ask is effectively MySQL's domain.
It can be accomplished in two statements:
Use an INSERT INTO statement to copy the rows from the old table to the new one
Delete the old table
My preference would be that this occurs in a stored procedure for sake of a transaction and ease of execution (in case you want it initiated by CRON/etc) because it would be easier to call one thing vs a couple or more.
27k is not very big table and MySQL should work ok with that. Do you have all the required indexes? Did you used EXPLAIN on your slow queries?
As for the question about moving data from one table to another - create a php script that will be run by CRON and will move rows one by one. What's the problem here?