PHP MySQL Insert fail after DELETE - php

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.

Related

delete using where and or

I have a database table [id,first,second,third] with a lot of entries and I would like to delete all the entries when [first,second,third] are empty.
Can I use WHERE and OR?
Here is my code I would like to use. However, it might show some errors:
$sql= "delete * from mytable where first='' or second='' or third=''";
mysql_query($sql) or die("query failed: $sql".mysql_error());
You don't need * in this statement.
$sql= "delete from mytable where first='' or second='' or third=''";
Remove the star
$sql= "delete from mytable where first='' or second='' or third=''";
You don't need that with the delete statement
It's delete from, not delete * from
Adding something new to what hasn't already been said:
The asterisk isn't something that DELETE can use, only SELECT can. Yet what I am adding here is that an (mysql) aggregate function such as COUNT() can also use the asterisk.
An basic example:
SELECT COUNT(*) AS Total
FROM products
Here are their respective references:
https://dev.mysql.com/doc/refman/8.0/en/delete.html
https://dev.mysql.com/doc/refman/8.0/en/select.html
https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html
Notes:
Some coders who are new to working with databases who used a SELECT query for something that worked for them, might have thought that using the asterisk (a.k.a. "star") in a DELETE statement uses the same syntax as SELECT and that it would delete everything. It's logical though, but it doesn't quite work that way with DELETE.
What needs to be used would either be TRUNCATE or DROP TABLE depending on what you want to do exactly. Delete just the selected records, all of the records or the table itself? The decision is yours.
For a specific record, use the WHERE clause.
Warning
Be careful with DROP TABLE, it will delete everything including any existing columns empty or not and their definitions.
Use TRUNCATE to only delete all of the records and not the columns and their definitions.
Please consult the manuals before usage:
https://dev.mysql.com/doc/refman/8.0/en/truncate-table.html
https://dev.mysql.com/doc/refman/8.0/en/drop-table.html
Footnote:
For those (re)visiting the question, please note that the mysql_* api is deprecated and deleted (no longer supported) in PHP 7.0.
Upgrade to either the mysqli_* or PDO api.
Consult the following references:
http://php.net/manual/en/migration55.deprecated.php
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php

Problem with PHP/MySQL Insert

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

mysql: transaction? insert and update

I need to do 2 query.
Basically it's a
mysql_query("INSERT INTO table ($value1,$value2)");
and
mysql_query("UPDATE table2 SET field1 = '$value1', field2 = '$value2'");
I think I can simply do a
if (mysql_query("INSERT ...") !== false) {
mysql_query("UPDATE ...");
}
In this case should I use a transaction? And how should I use it?
Or can i leave that simple if?
Thanks
You will generally use transactions if you want some "all or nothing" behavior.
Basically, with transactions, you can :
Start a transaction
Do the first query
If it succeeds, do the second query
If it succeed, commit the transaction
Else, rollback the transaction -- cancelling both queries that correspond to that transaction.
If working with mysql_* function, you'll have to :
Start the transaction, with a START TRANSACTION query
Do your queries
Depending on the result of those queries, either do a COMMIT or a ROLLBACK query.
To detect whether a query succeeded or not, you can indeed check the return value of mysql_query() : it will return false in case of an error.
Note : MySQL is the old extension -- and doesn't have functions to deal with transactions ; which means you have to deal with them as regular queries.
Working with MySQLi, you could use :
mysqli::autocommit() to disable autocommit
and mysqli::commit() or mysqli::rollback()
For insert and updates MySQL has a good, alternative solution - "ON DUPLICATE KEY UPDATE". It does what you want safely in a single query:
INSERT .... ON DUPLICATE KEY UPDATE
(also the key must be set as unique in this scenario)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

MySQL Multi-Insert? MySQL DB integrity after failed INSERT

Is it possible to insert a row into multiple tables at once? If you do several tables related by an ID; what is the best way to ensure integrity is maintained in case an INSERT fails?
That's exactly what transactions are for. If any of the commands fail, the whole thing since START TRANSACTION is rolled back:
START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'foo','bar');
INSERT INTO someothertable VALUES (LAST_INSERT_ID(),'baz');
COMMIT;
This being MySQL, you can't use transactions with MyISAM tables (you'll need the tables to use some engine that supports this, probably InnoDB).
This will never be inserted into the table (normally you'd have some branching, e.g. an IF):
START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'data','somemoredata');
ROLLBACK;
Caveat: SQL commands which change the database structure (e.g. CREATE,ALTER,DROP) cannot be rolled back!
Use transactions, luke.
MySQL can insert multiple rows (search for 'multiple rows') like this:
INSERT INTO table (field1, field2, ...) VALUES (value1, value2), (value3, value4), etc...
However, there's no way to tell what got inserted and what wasn't due to constraint violations, beyond the query returning a count of records, duplicates, and warnings. You also can't use last_insert_id() to figure out the IDs of the new rows, as that only returns the LAST id that was created, not a set of ids.
If you need to guarantee integrity, then use single row insert statements and transactions.

Postgresql and PHP: is the currval a efficent way to retrieve the last row inserted id, in a multiuser application?

Im wondering if the way i use to retrieve the id of the last row inserted in a postgresql table is efficent..
It works, obviously, but referencing on the serial sequence currval value could be problematic when i have many users adding rows in the same table at the same time.
My actual way is:
$pgConnection = pg_connect('host=127.0.0.1 dbname=test user=myuser password=xxxxx')or die('cant connect');
$insert = pg_query("INSERT INTO customer (name) VALUES ('blabla')");
$last_id_query = pg_query("SELECT currval('customer_id_seq')");
$last_id_results = pg_fetch_assoc($last_id_query);
print_r($last_id_results);
pg_close($pgConnection);
Well, its just a test atm.
But anyway, i can see 3 issues with this way:
Referencing on the customer_id_seq, if two user do the same thing in the same time, could happen that them both get the same id from that way... or not?
I have to know the table's sequence name. Becose pg_get_serial_sequence dont works for me (im newbie on postgresql, probably is a configuration issue)
Any suggestion/better ways?
p.s: i can't use the PDO, becose seem lack a bit with the transaction savepoint; I wont use zend and, in the end, i'll prefer to use the php pg_* functions (maybe i'll build up my classes in the end)
EDIT:
#SpliFF(thet deleted his answer): this would works better?
$pgConnection = pg_connect('host=127.0.0.1 dbname=test user=myuser password=xxxxx')or die('cant connect');
pg_query("BEGIN");
$insert = pg_query("INSERT INTO customer (name) VALUES ('blabla')");
$last_id_query = pg_query("SELECT currval('customer_id_seq')");
$last_id_results = pg_fetch_assoc($last_id_query);
print_r($last_id_results);
//do somethings with the new customer id
pg_query("COMMIT");
pg_close($pgConnection);
If you use a newer version of PostgreSQL (> 8.1) you should use the RETURNING clause of INSERT (and UPDATE) command.
OTOH if you insist on using one of the sequence manipulation functions, please read the fine manual. A pointer: "Notice that because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did."
Insert and check curval(seq) inside one transaction. Before commiting transaction you'll see curval(seq) for your query and no matter who else inserted at the same time.
Don't remember the syntax exactly - read in manual (last used pgsql about 3 years ago), but in common it looks like this:
BEGIN TRANSACTION;
INSERT ...;
SELECT curval(seq);
COMMIT;
ex. minsert into log (desc,user_id) values ('drop her mind',6) returning id

Categories