mysql update query on two tables - php

I am trying to update two tables in one query using a query that looks like this:
$query = "UPDATE tblproducts, tblsideimages
SET tblproducts.prodCode='oj', tblsideimages.prodCode='oj'
WHERE tblproducts.prodCode='aj'
AND tblsideimages.prodCode='aj'";
It works if there are contents in tblsideimages such as that one but it doesn't work if tblsideimages has no contents.
The problem is that I have to make it adjust accordingly because it is not always that there will be a content in tblsideimages. Sometimes the user can add data that is inserted in tblproducts only. How can I make it that, if there is no content in tblsideimages, it will still work for tblproducts and if tblsideimages and tblproducts both has content, both will update. Thanks!

There is no way (and real reason) to do all the work in one query. So just split it into:
UPDATE tblproducts SET prodCode='oj' WHERE prodCode='aj'
UPDATE tblsideimages SET prodCode='oj' WHERE prodCode='aj'
Less queries doesn't mean "more performant", so never follow the idea to fit everything into one query.

you could do this with a stored procedure - write a stored procedure with the update statements in a transaction.
Using rollbacks, you can ensure that they are treated as one unit of work, ie either they are all executed or none of them are, to keep data consistent.
or execute multiple queries like
$query="UPDATE tblproducts
SET tblproducts.prodCode='oj'
WHERE tblproducts.prodCode='aj';
UPDATE tblsideimages
SET tblsideimages.prodCode='oj'
WHERE tblsideimages.prodCode='aj'";

Related

Transferring data from one table to another using a where clause mysql

I would like to copy data from one table to another, but placing it in a specific row. The variable is set, the tables and query are named correctly and the columns set up correctly.
I would like to select the data circled in black
and place it within the section circled below in black
The query I am using if below. When it runs without the WHERE clause it goes on the row below, when the WHERE clause is added it is blank.
$query = "INSERT INTO Results (Q1A) SELECT Q1AY FROM Answers WHERE User = $email";
Try
$query ="UPDATE Results R SET Q1A= (SELECT Q1AY FROM Answers) WHERE R.User=$email"
This only works if there are only one row in Answers, but your code seems to assume as much.

Clarifications about Multi Queries

I'm trying to execute 2 queries, but whenever I follow the guides online about multi queries, its not doing either of the queries.
What I'm trying to do on the first query is to INSERT or ADD whatever the user inputs on $HISTORY on the record that's currently on colHistory; I.E.:
Current data on colHistory:
A
User inputs 'B' on $HISTORY, the syntax should add 'B' on the 'A' that's currently on record, or 'AB'. Then use the second query to UPDATE all the other records or columns on this particular row.
Here's the code (Please note that the '...' means more code that's unnecessary):
$query = INSERT INTO tbInventory SET colHistory='$HISTORY' WHERE colSerno='$SERIALNUM';";
$query .= "UPDATE tbInventory SET
colImage='$IMAGE',
colSerno='$SERIALNUM',
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
mysqli_multi_query($con,$query);
Please note where I declared colHistory as '' before I insert the data from the form. I'm not sure if I'm doing it right on this part. Is there anything that I'm missing?
*Edit:
I have already tried executing the queries one by one as:
mysqli_query($con,"INSERT INTO tbInventory SET colHistory='$HISTORY' ");
mysqli_query($con,"UPDATE tbInventory SET
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
Yet it doesn't seem to work either, the whole thing gets ignored.
(** I have a script below the code block above where I could print the results already, and it does run)
Well I can tell you why your first query is broken.
INSERT INTO tbInventory SET colHistory='$HISTORY'
This query is using UPDATE syntax but you are telling the query processor to expect INSERT INTO syntax. So the query is unable to execute.
Decide whether you are needing to UPDATE an existing record or INSERT a new one and alter your query to reflect that. (Change INSERT INTO to UPDATE or change "Set colHistory = '$ History'" to "Values ('$ History', 'col2Val', and so on..")
As for your second query, the syntax looks alright from what you have shown but since you didn't post the entire query its hard to say what is happening there. If you can show more of that query I can update this response.
Here's a good SO question on inserts vs updates.
What are differences between INSERT and UPDATE in MySQL?
I ended up dropping the multi-query method and I did got my intended results by somehow cheating:
I assigned the old data or the data that's currently on the colHistory cell, displayed it, but I disabled the textarea. I then created one more hidden textbox in the script with the old data in it and then hid it to the users view.
I then concatenated both textareas with the new one that I've created that the user could modify, emulating the results wanted.

Is it possible to add a add a number after select a value?

I trying to add +1 in a column after select but its not working, what I want is, when I make a search, the scripts adds +1 in a column to track how much searches I did.
Heres how it is now
$QUERY = "SELECT company FROM test WHERE number = '$number[0]' LIMIT 1";
And I want to add this
UPDATE users SET consultas=consultas+1 WHERE username = '$username'
If I add another $QUERY line the script breaks, any ideas ?
By nature, SELECT queries are for returning information from the database, not updating the database. To this end, triggers aren't even available for SELECT queries to react to the action. As such, if you want to increment a value, this must be done in a separate query, as an UPDATE query or possibly an INSERT ... ON DUPLICATE KEY UPDATE query if that better suits your needs.
You should execute those as two separate queries. Also, be very careful to ensure your data is properly escaped because it looks like you've forgotten to do that.
Be sure to check the result code of each as an error may occur at any time. If you use PDO there's a fairly robust error handling pattern you can follow.

Can I perform concurrent request and modificatio using PDO

I have a mysql table with a lot of data in it. All of the rows in this table need to have one field modified in a way that is not easily expressed in pure SQL.
I'd like to be able to loop over the table row by row, and update all the entries one by one.
However to do this I would do something like:
$sql = "SELECT id,value FROM objects";
foreach ($dbh->query($sql) as $row)
{
$value = update_value( $row['value'] );
$id = $row['id'];
$update_sql = "UPDATE objects SET value='$value' WHERE id=$d";
$dbh->query( $update_sql );
}
Will this do something bad? (Other than potentially being slow?)
Clarification: In particular I'm worried about the first select using a cursor, rather than retrieving all the data in one hit within the foreach, and then
there being something I don't know about cursor invalidation caused by the update inside the loop. If there is some rule like "don't update the same table while scanning it with another cursor" it's likely that it will only show up on huge tables, and so me performing a small test case is pretty much useless.
If someone can point me to docs that say doing this is OK, rather than a particular problem with working this way, that'd also be great.
The results of a single query are consistent, so updates won't affect it. To keep in mind:
Use prepared statements; it will reduce the traffic between your process and the database, because only the values are transferred instead of a whole query every time.
If you're worried about other processes running at the same time, you should use transactions and proper locking, e.g.
// transaction started
SELECT id,value
FROM objects
LOCK IN SHARE MODE
// your other code
// commit transaction
Seems like you have two options right out of the gate:
(straight-forward): use something like 'fetchAll' to get all the results of the first query before you start looping through it. this will help keep you from overlapping cursors.
(more obscure): change this to use a stored function (in place of 'update_value') so you can turn the two queries into a single 'update objects set value=some_function( id )'
Depending on the size and duration of this you may need to lock everything beforehand.

Mysql multiple OR statements

So I have a table with a column called id and in some rare cases a lot of the IDs(between 20-140 different IDs) listed don't need to be/can't be shown to the user. It's all based on different permissions.
SELECT * FROM `table` WHERE (`id` != 21474 OR 26243 OR 78634) AND `checked` = 5
Unfortunately there is no additional grouping anywhere else in the DB that allows me to call out this section of IDs at once. So I'm looking if there is a better way of going about this or if I should ignore doing this during the mysql/SELECT statement and instead do it within like a PHP statement after everything is pulled. The problem with a PHP foreach later is the data that is pulled can be hundreds upon hundreds of rows so it will really slow down the page. As you can see in the above mysql query I was thinking of just listing out the IDs in one huge statement but I figured maybe there is a better way of going about this. 100 ORs just doesn't sound like the best possible solution.
Use the IN keyword,
SELECT * FROM `table` WHERE `id` NOT IN (21474, 26243, 78634) AND `checked` = 5
IN statement is good, but be careful not to bump into max_allowed_packet option of the server, if you query turns out toooooo long.

Categories