I have 4 queries that run on a post. I've noticed that not all the queries are working if one of the first queries have no work to do.
Here are my queries
mysql_query("UPDATE invoice SET company='$company' WHERE company='$oldcompanyname'") or die(mysql_error());
mysql_query("UPDATE bill SET customer='$company' WHERE customer='$oldcompanyname'") or die(mysql_error());
mysql_query("UPDATE project SET customer='$company' WHERE customer='$oldcompanyname'") or die(mysql_error());
mysql_query("INSERT INTO activity_log (item, date) VALUES ('Customer Editted', NOW()) ") or die(mysql_error());
To give you an example, the first one runs ok. But the second one has no work to do because the data in the field does not exist. The third and the fourth should run but they do not.
I have always been accustomed to appending my queries with "or die(mysql_error());" but I'm thinking now that is not the best choice. But shouldn't the remaining queries run even if the one in the middle has no work to do?
If there is work to be done in all 4, then it works fine.
#HamZa DzCyberDeV is right, if one of your first queries fails, the die() call will stop the rest of your script from executing just like exit(). You are much better off removing the die statement and using if/else in cases where you need to run a query only if another one completes.
$result = mysql_query("UPDATE invoice SET company='$company' WHERE company='$oldcompanyname'");
if ($result !== false) {
// do something here or execute the next query
}
Also, don't use mysql_* functions in new code Why shouldn't I use mysql_* functions in PHP?. They are no longer maintained and are officially deprecated https://wiki.php.net/rfc/mysql_deprecation. Learn about Prepared statements https://en.wikipedia.org/wiki/Prepared_statement instead, and use PDO http://php.net/pdo or MySQLi http://php.net/mysqli.
This sounds like you should just normalize your data. If you had your customer table linked based off of an ID, you could just do:
UPDATE `company` SET name='$new_name' WHERE company_id=$id
And then in your invoice/bill/project tables you would have a foreign key for company_id, instead of basing it off of company_name.
Related
This is quite a basic question, but have not found that much on-line to support.
I need to use a simple update statement in mysql (I know i should use mysqli but not yet ready for this update)
Given That I am working with a database made of a fixed number of items I want that the update apllies only when 2 conditions together are true.
my idea is something like
$sql ="update `members` set `description`='$description[$index]' WHERE id='1' AND fruit = 'banana'";
Is this the proper way of selecting the record to be updated?
Many thanks
Manu
That's how you'd do it more or less, here's a refined one:
$sql ="update `members` set `description`=? WHERE `id`='1' AND `fruit` = 'banana'";
1) See how I put the ? instead of the array? There are smart objects in PHP (read about "Prepared Statements") which allow you to put a parameter "spot" in the query and later have a value instead of it. This makes your query much more secure.
2) I added '`' around your columns. It's not mandatory, but it makes sure that your columns aren't mistaken for something else.
Yes that should work but it's safer to wrap array values in a string in brackets:
$sql ="UPDATE `members` SET `description`='{$description[$index]}' WHERE id='1' AND fruit = 'banana'";
Also make sure $description is somehow filtered or validated, before plugging it directly into the string.
NOTE: Best practice dictates that you use all caps for all SQL keywords, allowing easier differentiation between keywords and your values. Yours has half and half update and set lowercase; WHERE and AND caps, which is worse than going with all lowercase.
[edit] I agree with Daniel Saad that you should be using prepared statements here as well.
I'm working on a site in which I have to insert values in different table. so keeping this need in view, is it possible for me that can I use multiple query in single mysql_query in php or not.
for example:
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'); insert into tableB (xxx, xxx, xxx) values ('value1','value2','value3')")
I want to run multiple queries in single statement. Please suggest some solution.
No, it is not possible. The obsolete mysql_* API only allows for one query to be executed at a time. To do this you need to use the mysqli API and mysqli_multi_query().
A single MySQL "INSERT" statement can support multiple VALUE tuples if they're for the same table.
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'), ('yyy','yyy')")
However, what you're trying to do is not possible with the mysql_* functions.
Although the mysqli_* API allows you to run multiple queries at once, I recommend you AGAINST doing that for at least 2 reasons:
It's always a good (actually, great) idea to use prepared statements, for security reasons. Prepared statements can be used with the MySQLi API as well as with PDO.
As you can see from the docs for mysqli_multi_query(), getting errors from that function can be cumbersome. The function, indeed, returns only "false" if the first query fails; to get results for other queries you need to call another function.
In general, why would you need to combine multiple queries together? Eventually, the time you'd save would be minimal.
Instead, if your goal is having more than one query executed together, and having the whole set of queries fail if one fails, you can use transactions (which also can speed up inserts in some cases). Both MySQLi and PDO support transactions: see examples here for PDO http://php.net/manual/en/pdo.transactions.php
PS: in general, it's a good idea to avoid using mysql_* functions entirely, as those APIs are deprecated.
Welcome to PDO:
With PDO am able to do something like:
$sql = "
insert into tableA (e_mail, name) values (:e_mail, :name);
insert into tableB (xxx1, xxx2, xxx3) values (:xxx1, :xxx2, :xxx3)
";
Just have the Query Prepared first then VOILA!!
OR Using the Transaction method:
$con->beginTransaction();
$sql1 = "insert into tableA (e_mail, name) values (:e_mail, :name)";
$sql2 = "insert into tableB (xxx, fff) values (:xxx, :fff)";
$sql3 = "insert into tableC (qqq, bbb) values (:qqq, :bbb)";
$con->commit();
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.
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
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