How to insert data into two or more tables?
Currently I am using this trick. (Let just assume that the syntax is correct)
$Sql1 = "insert into user";
$Sql2 = "insert into files";
$Sql3 = "insert into messages";
query $Sql1
query $$ql2
query $Sql3
So I am using this and I need to optimize.
Also, I think I need to use Foreign key? But I don't know how to do it on phpmyadmin.
and lastly:
This is all I want.
To insert data on the "user" table and then automatically the table "messages" and "files"
will have also an ID which is the same with the user.. That is why I use to 3 queries in my code.
Please help me.
Thanks in ADVANCE!
myb
It is perfectly fine to use multiple queries.
However, you should wrap the 3 queries into one transaction. That is, if one query fails for some reason, the effects of all previous queries (if any) can be rolled back so that your database stays in a consistent state.
Note: Transactions are not possible with MySQL's MyISAM tables. Additionally you have to use PHP's Mysqli (or PDO) to be able to use transactions. (I assume that you're not using some high-level data base abstraction layer.)
As to your question regarding foreign keys: As far as I know, it makes no difference when you're using the MyISAM engine for the tables in your database (which I presume), because MyISAM doesn't even support the explicit modeling of foreign keys. Other table engines like InnoDB, however, can use foreign keys to check certain constraints like "a message must always be associated with an existing person".
Here are some nice examples regarding foreign keys: http://www.postgresql.org/files/documentation/books/aw_pgsql/node131.html
This is the answer, I think : http://dev.mysql.com/doc/refman/5.1/en/example-foreign-keys.html
With mysql u can use LAST_INSERT_ID() or in php mysql_insert_id() function. Checkout this manual entries:
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://php.net/manual/en/function.mysql-insert-id.php
Related
Lets say I have this PHP function:
function strlow($string){
strtolower(trim($string));
}
Now lets say I have a table with 2 columns [id - title] and I want to make all titles that are going to be inserted into the table in lowercase, The usual way is
$title = strlow($title);
$query = "INSERT INTO table (title) VALUES ($title);
Is there for example a way to implant in the column itself in the database the function, So instead of doing the strlow() by the PHP, the Database does it?
If yes, I wish for an example built on mine.
You could update your query to handle this if you really wanted (but I would still rather do this in the application layer) using the MySQL TRIM and LOWER commands:
INSERT INTO table (title) VALUES (TRIM(LOWER(($title)))
The reason I say I would rather do this in the application layer is that if you decide to switch database systems in future, you need to remember to port over all your database formatting rules such as these at that time too which although doesn't seem too bad now, trust me, in the future, you will forget.
In addition to this, if you ever want to add further logic to what you are putting in to the database you will likely find your options more limited in MySQL than you will in your application layer.
Also, please for my sanity look up how to use parametrized queries because you are wide open to SQL injection attacks at the moment. There is a great post here that covers this.
$query = "INSERT INTO table (title) VALUES (LCASE($title));
I'm using the PDO class to connect to mysql becuase I noticed that it's the best and surest way to do it. I noticed also that i can't use PDO parameter in tables name so I saw this question: Can PHP PDO Statements accept the table or column name as parameter?
I use in my application a GET parameter as a table name and now my question is:
It's better to use
function buildQuery( $get_var )
{
switch($get_var)
{
case 1:
$tbl = 'users';
break;
}
$sql = "SELECT * FROM $tbl";
}
or just give a "show tables" in MySql and compare every single table resulted from this command to the table passed via GET?
Thank you all!
Although "Just give a "show tables" in MySql and compare every single table resulted from this command to the table passed via GET" approach is flawed, it is not the main problem.
You are no the first one who, having no basic knowledge on database design, inventing yet another square wheel and then come to the community for help to make it move.
You need to rewind your ideas back some.
And reconsider database design, which should never involve dynamical tables, each of them used as a some sort of plain text file, queried with just SELECT * FROM table.
Please learn some relational database design basics first, then create a sensible design, then query your tables the way everyone do it: keep all the data in one table and use WHERE clause to get specific data.
Youre first solution is fine.
But don't pass the tablename via get. just pass a number which you can lookup via switch the table name.
I got two tables. One is account, another is Interest.
One account can have multi Interests and It can be edited.
Now, the process is deleting all Interest of this account then insert these insterests.
The QUERY IS:
"DELETE FROM Interests WHERE account_id='$id'"
"INSERT INTO Interests (account_id, interest_name) VALUES('$id', '$name')"
I use the both query when user update their account, but the insert is fail, there is nothing insert into the table (ps. the interests_id is auto_increment and this was be counted) but there is nothing new in the table. When I comment out the delete query. The insert will be successful.
Does any one know what can i do?
If you want to update your table records, you will do update operation.
like this:
UPDATE TABLE_NAME SET FIELD_NAME = 'VARIABLE_NAME'
WHERE PRIMERY_FIELD_NAME = 'VARIABLE_NAME' ;
you did not have to use these two queries, if you want to update data simply use the updat query of mysql.use this:
<?php
$query = "UPDATE Interests SET interest_name = '".$name."' WHERE account_id = '".$id."'" ;
mysql_query($query);
?>
If you want to update your table records then you may execute update operation. It like following
UPDATE Interests
SET
interest_name = '$name'
WHERE
accountno = '$id' ;
Try it. You may solve your problem by this way.
If you have queries failing, you should capture the error and see what went wrong. In all MySQL APIs for PHP, a query that fails returns a status code to indicate this. Examples of checking this status code are easy to find in the docs. But most developers fail to check the status.
Use transactions to ensure that both changes succeed together or neither are applied.
How to Decide to use Database Transactions
Definition of a transaction in MySQL: http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_transaction
Syntax for starting and committing transactions in MySQL: http://dev.mysql.com/doc/refman/5.5/en/commit.html
You need to use InnoDB. MyISAM does not support transactions. http://dev.mysql.com/doc/refman/5.5/en/innodb-storage-engine.html
In PHP, you need to stop using the old ext/mysql API and start using MySQLi or PDO.
http://php.net/manual/en/mysqli.quickstart.transactions.php
http://php.net/manual/en/pdo.begintransaction.php
This happens because the query are treated as two single transaction, so the order of execution is not guaranteed.
The effect you are describing is because the insert is processed before delete, so the interests_id is auto-incremented properly, then the row is deleted by delete statement.
You should change the query logic or perform both queries in one single transaction.
In php, I'm trying to insert a value into one table, return an auto-incremented value, and then insert that value along with other values into a second table.
I'm running into a few problems. First, while there's a lot of ways of doing this in SQL, I have to do this with php's mysql functions. I'm afraid of weird errors if I combine multiple statements together. Second, like I mentioned, I need this to be done in one query, as it'll be used for a web application.
My current query is like this
INSERT INTO TABLE1 VALUES(*);
INSERT INTO TABLE2
SELECT max(AutoIncrementedColumn)
FROM TABLE1;
The problem I'm having is that mysql_query() doesn't support multi queries. Also, I believe mysql_escape_string() removes anything it believes to be a multi query, so even if I could somehow get mysql_query to believe my query is not a multi query, I'm still out of luck unless I write my own escape method.
Does anyone have any ideas on how to deal with this problem?
EDIT: Forgot to mention that I can't use mysql_insert_id because the column that's autoincrementing is of type Bigint.
I have these tables: My final mysql db, could someone check if the tables are correctly made?
How can I make an Insertion of an ad here?
Is join used on insert also?
Thanks
Clarification: I need to insert values into multiple tables here, and don't know how to do it else than using multiple INSERT INTO statements.
So I wonder if there is anyway to make just ONE statement (one line) and use JOIN to INSERT?
As far as I'm aware of, you can't INSERT data into multiple tables Within one plain SQL statement.
There are many database abstraction frameworks out there which can do something like that (DOCTRINE TO THE RESCUE!!) but thats a whole other story.
SQL for it self it not capable of such things.
No it's not possible with an INSERT statement to insert into multiple tables. But you could use a stored procedure that would nicely batch the various inserts, and the application would have only one SQL command to emit.
I don't understand your first question about the ads. As for the second, JOIN will not be used on a standard table unless you are using it in an INSERT...SELECT statement, which you very likely aren't.