I am trying to update a MySQL database field (decrease the value by 1) in a specific row (ID) of the "places" column, as long as the number in the field is greater than 0.
(see the example statement below)
UPDATE table SET places = places - 1 WHERE id = $id AND places > 0
The statement below fails apart from changing the value of the field to zero.
I would be grateful if anyone can help with the syntax error.
if($id){
global $modx;
$table = "`database_name`.`table_name`";
$update_seats = "`places` - 1";
$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
return $result; // Returns 'true' on success, 'false' on failure.
}
You have enclosed new value of field in double quotes
$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
what is evaluated as string in MySQL query. Remove double quotes here
'`places` = "' . $update_seats . '"'
so that it looks like this
$result = $modx->db->update( '`places` = ' . $update_seats, $table, '`id` = "' . $id . '" AND `places` > 0' );
The query looks ok, if you need to set minimum value of 1 to places you should simply change the query accordingly:
UPDATE table SET places = places - 1 WHERE id = $id AND places > 1
Related
This question already has an answer here:
Count always returns 1...but does it exist?
(1 answer)
Closed 3 years ago.
function c_save( $a, $status, $b ) {
global $db;
$st = $db->query( "select count(id) from steps where cas = '" . $a . "' and status = '" . $status . "' and title = '" . $b . "'" );
$count = $st->rowCount(); echo $count;
}
the echoed result - 1
Manually checking the table (20 rows total) - there is no such a row having cas = $a... so the result should be 0.
you are performing the count at the query level. the result of your query is a single line containing maybe 20.
if you want to get the number of records ', you can just get the value returned by the query or do not count within sql to get the full resultset and let php make the count.
Try this:
function c_save($a, $status, $b){
global $db;
$st = $db->query("select id from steps where cas = '" . $a . "' and status = '" . $status . "' and title = '" . $b . "'");
$count = $st->rowCount();
echo $count;
}
I have the following query:
REPLACE INTO `oxarticles`
SET
OXID = '10-1010',
oxartnum = '10-1010',
oxtitle = 'Dummy',
oxprice = '10.000000',
oxstock = '100',
importstatus = 1"
This works so far as expected, but the fields I do not specifiy, are just overwritten with ' ' / empty string. From what I read, should this syntax work identically like the UPDATE-command.
Am I missing something? How can I prevent that fields are replaced with '' ?
Edit 1
Just to clarify, I can't just use UPDATE. I am setting a flag (importstatus) to 0 before every run and during the import to 1. After the import finishes, I delete all articles, which are still on status 0.
// Just for the compeletion, here is the PHP-snippet:
while (!feof($this->handle))
{
$row = fgetcsv($this->handle, 0, ";");
$sSql = "REPLACE INTO oxarticles SET "
. " OXID = '" . $row[0] . "', "
. " oxartnum = '" . $row[0] . "', "
. " oxtitle = '" . $row[1] . "', "
. " oxprice = '" . str_replace(",", ".", $row[4]) . "', "
. " oxstock = '" . str_replace(",", ".", $row[5]) . "', "
. " importstatus = 1";
// $sSql = "UPDATE oxarticles SET oxtitle ='" . $row[1] . "', oxprice='" . $row[4] . "', oxstock='" . $row[5] . "' WHERE oxartnum ='".$row[0]."'";
$this->db->execute($sSql);
}
From the mysql documentation:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted. See
Section 13.2.5, “INSERT Syntax”.
In other words, the row is being deleted and then inserted, hence your old values aren't staying intact. Perhaps you could select the original row first, and feed those values back in where appropriate.
You query will replace old data into new data if you do not provide data for a field it will set to null . If you do not want to loose your data just want to update field use on duplicate key update.
If did't found any match it will insert new row
If found it will replace data if provide
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8) ON
DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;
I started learning php, I'm having some problems with this mysql query
mysql_query( "UPDATE boardinfo SET totalPostCount = '" . $GLOBALS['postCount'] + 1 . "' WHERE boardName = '" . $_POST['board'] )
Error: near '1' WHERE boardName = 'Site' at line 1
All I need to do here is to update the value of totalPostCount if it's boardName matches value from $_POST['board']
Please, go easy on me, I've only started this yesterday...
In your statement, quotes are not closed in last.
mysql_query( "UPDATE boardinfo SET totalPostCount = '" .$GLOBALS['postCount'] + 1 . "' WHERE boardName = '" . $_POST['board']."'" )
If it doesn't solve your issue,try one more thing.
$val = $GLOBALS['postCount'] + 1;
mysql_query( "UPDATE boardinfo SET totalPostCount = '" .$val . "' WHERE boardName = '" . $_POST['board']."'" )
Hope it will solve your problem
I am trying to use the result of one mysql query in another mysql query, but I'm obviously doing something wrong. This is what I have:
<?php
$result = mysql_query('SELECT panel_product_no
FROM panelProduct
WHERE length_mm = "' . ($_POST["p_length_mm"]) . '"
AND width_mm = "' . ($_POST["p_width_mm"]) . '"
AND veneer_type = "' . ($_POST["p_veneer"]) . '"
AND lipping = "' . ($_POST["p_lipping"]) . '"');
$panel = mysql_fetch_array($result);
?>
And then I want to use that in this bit:
<?php
if(!empty($_POST[p_length_mm]) && !empty($_POST[p_width_mm]) && !empty($_POST[p_aperture]))
{
$sql3="INSERT INTO estimateDescribesPanelProduct (estimate_no, panel_product_no, quantity)
VALUES ('$_GET[estimate_no]','$panel','$_POST[p_quantity]')";
if (!mysql_query($sql3,$con))
{
die('Error: ' . mysql_error());
}
}
?>
The query is basically working in that it is inserting the posted estimate_no and quantity into the DB, but not the correct panel_product_no (it just inserts '0'). How can I get it to insert the $result value?
P.S. I know that I should not be using mysql functions and I will not be in future, however I am so nearly finished with this project that at this point I am not in a position change.
Your are basicly copying content from one table to another.
Wy not use the MySQL INSERT .. SELECT syntax?
as #Dmitry Makovetskiyd wrote, mysql_fetch_array() returns a resource, not manipulatable results.
For example:
$result = mysql_query('SELECT panel_product_no
FROM panelProduct
WHERE length_mm = "' . ($_POST["p_length_mm"]) . '"
AND width_mm = "' . ($_POST["p_width_mm"]) . '"
AND veneer_type = "' . ($_POST["p_veneer"]) . '"
AND lipping = "' . ($_POST["p_lipping"]) . '"');
$resource = mysql_fetch_object($result);
You need to add in:
$panel = $resource->'panel_product_no';
You can then continue with your second query.
Note the change from mysql_fetch_array() to mysql_fetch_object() - as your query suggests you are only retrieving a singular value from the table (assuming there is only a singular panel with the specified length, width, veneer type and lipping), the object method will work fine.
I am a MySQL noob and basically hacking an insert query to become an update query instead. So I am sure it's something simple with the grammar. But what's wrong with this?
// Save data
$mySQLQuery = 'update `'. $fl['mysql_table']. '` SET '. $fl['mysql_query']. "' WHERE speres = '" . mysql_real_escape_string($_POST['speres']);
$rs = #mysql_query($mySQLQuery);
the original INSERT query (working) was
// Save data
$mySQLQuery = 'INSERT INTO `'. $fl['mysql_table']. '` SET '. $fl['mysql_query'];
$rs = #mysql_query($mySQLQuery);
The data is generated here:
$fl['mysql_query'] = "menrecin = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_17'])) . "', menrecvej = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_18'])) . "', menrecser = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_19'])) . "', menrecud = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_20'])) . "', menresmor = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_22'])) . "', menresfro = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_23'])) . "', menresmid = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_24'])) . "', menresres = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_25'])) . "', menrumind = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_28'])) . "', menrumren = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_29'])) . "', menrumved = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_30'])) . "', tekip = '" . $_SERVER['REMOTE_ADDR'] . "', tekbro = '" . $_SERVER['HTTP_USER_AGENT'] . "', tektid = NOW()";
I have an entry with speres = 100525 in the database, so please try:
http://www.konferencer.nu/form/index.php?speres=100525
Good practices of troubleshooting dynamic SQL:
Look at the SQL, not the code that builds the SQL. In other words, echo out $mySQLQuery to see the final SQL, and most of the time you can see the error right away.
Don't suppress errors. Error-checking is helpful and necessary in any code.
It looks to me like your query ends up being:
update `tablename` SET ..., tektid = NOW()' WHERE speres = '...;
So you have a spurious quote after the NOW() and a missing quote at the end.
If you had checked for errors, you'd get something like this:
ERROR 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for
the right syntax to use near '' WHERE speres = '...' at line 1
The quoting around the start of the WHERE clause looks odd:
UPDATE `...some table...` SET ...some query... 'WHERE speres = ' ... some criterion ...
Note the single quote placement. Maybe you want to remove the single quotes from inside the double quotes?
you query should look like
$mySQLQuery = 'update'. $fl['mysql_table'].'SET'. $fl['mysql_query'].'= <some value>' ' WHERE speres = '.mysql_real_escape_string($_POST['speres']);
$rs = #mysql_query($mySQLQuery);