Im trying to set a variable using sprintf via a Join Query, then update each time this appears in the table using the ID loaded into the query.
The update works fine if I use a slightly different query but one that gives an identical set of results, so have come to the conclusion Im doing something silly.
Here is a selection below:
//below is a simpler version of what I would like to work with the update
$sql=sprintf("SELECT `test`.`id` FROM `test` JOIN `test2` ON (test.agent=test2.user) WHERE `test`.`type`='new' AND `test2`.`note` = 'p';
//this is what works, even though the output (list of test.id) is identical to above
$sql=sprintf("SELECT `id` FROM `test` WHERE `test`.`type`='new' AND `agent`='test.user';
//here is my update that works with the second select
if($ref_id = mysql_one_data($sql)){
$updateSQL= sprintf("UPDATE `test` SET `type`='testdata', `priority`=%s, `note`=%s WHERE `id`=%s;",SQLVal('100', "int"),SQLVal($note, "text"),SQLVal($ref_id, "int"));
$result = mysql_query($updateSQL) or die(mysql_error());
$processed=TRUE; $result="updated";
$count_converted++;
}
Any ideas? I'm at a total loss! As I said both queries give 100% the same output, so the variable produced should be the same right? and so if one update works when it finds a corresponding value the other should too.
Related
I am refering to this post. I am stuck with a problem I can't resolve. I try to insert multiple rows with a php script into a MySQL database. I don't succeed in updating the whole thing using ON DUPLICATE KEY UPDATE and using a WHERE condition (at the end of the code below) I would like to use to update only an entry has been modified recently:
// for information (used in a foreach loop):
$args[] = '("'.$row['lastname'].'", '.$row['phone'].', "'.$row['lastModification'].'")';
// then:
$stringImplode = implode(',', $args);
// Where I am stuck - WHERE statement:
$sql = $mysqli->query('INSERT INTO table_name '. (lastname, phone, timestamp) .' VALUES '.$stringImplode .'ON DUPLICATE KEY UPDATE lastname=VALUES(lastname), phone=VALUES(phone) WHERE timestamp > VALUES(lastModification);
Everything works fine except I cannot set any WHERE condition at this point that involves multiples entries. Maybe the WHERE statement in this case is not intended to refer to a condition in this statement.
I was told to try with a database procedure using a JOIN statement and a temporary table with first all my entries and then querying some conditions. But I have to admit I don't understand very well how I could leverage such a table to update an other table.
Is there an easy and lovely way to use a "CASE WHEN" or an "IF" statement in this case?
Would something like
INSERT INTO ... ON KEY DUPLICATE UPDATE lastname = VALUES(lastname), phone = VALUES(phone)
CASE WHEN (timestamp > VALUES(lastModification)) THEN do nothing ...
or
...ON KEY DUPLICATE UPDATE... IF (timestamp > VALUES(lastModification)) ...
If anyone could help me, I would be very grateful.
EDIT: Since I will have many variables, could it be used in this way:
INSERT INTO ... ON KEY DUPLICATE UPDATE
IF(timestamp > VALUES(timestamp),
(
name = VALUES(name),
number = VALUES(number),
timestamp = VALUES(timestamp)
....many other variables
),
(
name = name,
number = number,
timestamp = timestamp
....many other variables)
)
You can use simple IF function in value like this:
INSERT INTO ... ON KEY DUPLICATE UPDATE
name = VALUES(name),
number = VALUES(number),
timestamp = IF(timestamp > VALUES(timestamp), VALUES(timestamp), timestamp)
If condition is not met, it will update timestamp with the same timestamp which already exists. It does not matter, because update to same values is optimized before it is even executed, so MySQL will not make real update. You should not afraid of some performance penalty.
EDIT:
IF works likes this:
IF(condition, returned when true, returned when false)
Maybe you need to switch those two arguments to fit your condition like you want.
Heyy i think i need to do a query inside a query.
Here is what i tried to do(it seems to work but it takes forever to load) :
$query="SELECT * FROM Table1";
$results=mysql_query($query);
while($row=mysql_fetch_array($results)){
$bnr=$row['COL 1'];
$usg=$row['COL 19'];
echo"$bnr hat $usg <br /> ";
$sqlupdate="UPDATE TABLE_1
SET
Usg='$usg'
WHERE
bnr = '$bnr'";
mysql_query($sqlupdate);
}
Yes, updating many rows individually will take a long time regardless of whether you're doing it inside another query.
But certainly running two queries on the same database, at the same time will not help the situation at all!
That said, the good news is that in your example you're able to perform the update entirely on the server using an update with a join.
UPDATE TABLE_1 as TDest
INNER JOIN TABLE1 as TSrc
ON TDest.bnr = TSrc.`COL 1`
SET TDest.Usg = TSrc.`COL 19`
I think the MySQL query that you want is:
update tdest t1 join
tdest t2
on t1.bnr = t2.`Col 1`
set t1.usg = t2.`Col 19`;
I am trying to update MySQL table with results extracted from another table using a while loop but its only updating the last result set.
here is the code
$qa=$db->query("SELECT *, (acq_subudget.RemBal-order_items.total_cost) AS rama FROM order_items, acq_subudget WHERE invoice_num='$ordnumber_update' AND acq_subudget.id=order_items.disc");
while($qa_data=$qa->fetch(PDO::FETCH_ASSOC))
{
set_time_limit(0);
$account_remaining=$qa_data['rama'];
$account_name=$qa_data['acq_subudget.disc'];
$account_id=$qa_data['id'];
$qa_update=$db->exec("UPDATE `acq_subudget` SET RemBal='$account_remaining' WHERE id='$account_id'");
}
i am using pdo
you are using fetch instead of fetchAll, fetch only gets the next row from the result set
As an aside, you can probably do this in a single statement without needing a loop:-
UPDATE acq_subudget
INNER JOIN order_items
ON acq_subudget.id = order_items.disc
SET acq_subudget.RemBal = acq_subudget.RemBal-order_items.total_cost
WHERE acq_subudget.invoice_num='$ordnumber_update'
Hi there i am working on PHP code that is selecting columns from two tables.
Here is my code:
$result2 = mysql_query("SELECT *
FROM `videos`, `m_subedvids`
WHERE `videos.approved`='yes' AND
`videos.user_id`='$subedFOR'
ORDER BY `videos.indexer`
DESC LIMIT $newVID");
while($row2 = mysql_fetch_array($result2))
{
$indexer = addslashes($row2['videos.indexer']);
$title_seo = addslashes($row2['videos.title_seo']);
$video_id = addslashes($row2['videos.video_id']);
$title = addslashes($row2['videos.title']);
$number_of_views = addslashes($row2['videos.number_of_views']);
$video_length = addslashes($row2['videos.video_length']);
}
When i try to print $indexer with echo $indexer; it's not giving me any results.
Where is my mistake in this code?
It seems to me like the key 'indexer' isn't in your results. It's hard to tell, since you haven't listed a definition for your table and you're using SELECT * so we can't see the names.
It makes the program easier to read later, if instead of SELECT *..., you use SELECT col1, col2, .... Yes, SELECT * will save you some typing right now, but you'll lose that time later when you or anyone else who works on your code has to check the table definition every time they work with that line of code.
So, try changing your query to explicitly select the columns you use. If it's an invalid column you'll get an error right away rather than this silent failure you're getting now, and you'll thank yourself later as well.
So long as videos.indexer is a unique field name among all tables used in the query you can change
$indexer = addslashes($row2['videos.indexer']);
to
$indexer = addslashes($row2['indexer']);
You don't need to (or can not) use the table name when referring to the result.
I'm having problems debugging a failing mysql 5.1 insert under PHP 5.3.4. I can't seem to see anything in the mysql error log or php error logs.
Based on a Yahoo presentation on efficient pagination, I was adding order numbers to posters on my site (order rank, not order sales).
I wrote a quick test app and asked it to create the order numbers on one category. There are 32,233 rows in that category and each and very time I run it I get 23,304 rows updated. Each and every time. I've increased memory usage, I've put ini setting in the script, I've run it from the PHP CLI and PHP-FPM. Each time it doesn't get past 23,304 rows updated.
Here's my script, which I've added massive timeouts to.
include 'common.inc'; //database connection stuff
ini_set("memory_limit","300M");
ini_set("max_execution_time","3600");
ini_set('mysql.connect_timeout','3600');
ini_set('mysql.trace_mode','On');
ini_set('max_input_time','3600');
$sql1="SELECT apcatnum FROM poster_categories_inno LIMIT 1";
$result1 = mysql_query($sql1);
while ($cats = mysql_fetch_array ($result1)) {
$sql2="SELECT poster_data_inno.apnumber,poster_data_inno.aptitle FROM poster_prodcat_inno, poster_data_inno WHERE poster_prodcat_inno.apcatnum ='$cats[apcatnum]' AND poster_data_inno.apnumber = poster_prodcat_inno.apnumber ORDER BY aptitle ASC";
$result2 = mysql_query($sql2);
$ordernum=1;
while ($order = mysql_fetch_array ($result2)) {
$sql3="UPDATE poster_prodcat_inno SET catorder='$ordernum' WHERE apnumber='$order[apnumber]' AND apcatnum='$cats[apcatnum]'";
$result3 = mysql_query($sql3);
$ordernum++;
} // end of 2nd while
}
I'm at a head-scratching loss. Just did a test on a smaller category and only 13,199 out of 17,662 rows were updated. For the two experiments only 72-74% of the rows are getting updated.
I'd say your problem lies with your 2nd query. Have you done an EXPLAIN on it? Because of the ORDER BY clause a filesort will be required. If you don't have appropriate indices that can slow things down further. Try this syntax and sub in a valid integer for your apcatnum variable during testing.
SELECT d.apnumber, d.aptitle
FROM poster_prodcat_inno p JOIN poster_data_inno d
ON poster_data_inno.apnumber = poster_prodcat_inno.apnumber
WHERE p.apcatnum ='{$cats['apcatnum']}'
ORDER BY aptitle ASC;
Secondly, since catorder is just an integer version of the combination of apcatnum and aptitle, it's a denormalization for convenience sake. This isn't necessarily bad, but it does mean that you have to update it every time you add a new title or category. Perhaps it might be better to partition your poster_prodcat_inno table by apcatnum and just do the JOIN with poster_data_inno when you need the actually need the catorder.
Please escape your query input, even if it does come from your own database (quotes and other characters will get you every time). Your SQL statement is incorrect because you're not using the variables correctly, please use hints, such as:
while ($order = mysql_fetch_array($result2)) {
$order = array_filter($order, 'mysql_real_escape_string');
$sql3 = "UPDATE poster_prodcat_inno SET catorder='$ordernum' WHERE apnumber='{$order['apnumber']}' AND apcatnum='{$cats['apcatnum']}'";
}