I am trying to have my function increment by 1 a value in mysql, but it only works for once - from zero to 1. Then it won't increment. I have noticed that I need to add (int) in order to get it do this, so I guess there is something to do with data type. Do you have any hints?
$mod_seq = $this->db2->query("select mod_sequence from tbl_release_info where release_id = '$release_id';");
$current_modsequence = (int)$mod_seq++;
$update_query_release_info = "update tbl_release_info set mod_sequence = '$current_modsequence' where release_id = '$rid';
You can do that with just SQL and in a single query like this
$this->db2->query("update tbl_release_info
set mod_sequence = mod_sequence + 1
where release_id = '$rid'");
The query in your question returns the number of rows, not the value you want from mod_sequence. Try this instead:
$query = $this->db2->query("select mod_sequence from tbl_release_info where release_id = '$release_id';");
$row = $query->row();
if (isset($row)) {
$mod_seq = $row->mod_sequence;
}
$mod_seq++;
$update_query_release_info = "update tbl_release_info set mod_sequence = '$mod_seq' where release_id = '$rid';
If the datatype of mod_sequence is not an integer, type cast it:
$mod_seq = (int)$row->mod_sequence;
Or like this:
$mod_seq = intval($row->mod_sequence);
EDIT: #RiggsFolly nailed the most elegant solution, by far, in a single query :-) https://stackoverflow.com/a/42194758/1363190
Related
I'm trying to run these following simple query (it works in postgresql)
update ja_clients set ref_inc_num = ref_inc_num + 1 where id = 43933 returning ref_inc_num;
into DQL
$query = $this->entityManager->createQuery();
$query->setDQL("UPDATE Geoop\Core\Entity\Account a SET a.jobReferenceNumber__ = a.jobReferenceNumber__ + 1 WHERE a.id = :accountId RETURNING a.jobReferenceNumber__");
$query->setParameter('accountId', $account->getId());
$total = $query->getSingleScalarResult();
but it doesn't work retuning this error:
#30 /var/www/geoop_api/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php (line 861): Doctrine\ORM\Query\Parser->syntaxError(end of string)
#31 /var/www/geoop_api/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php (line 448): Doctrine\ORM\Query\QueryException::dqlError(UPDATE Geoop\Core\Entity\Account a SET a.jobReferenceNumber__ = a.jobReferenceNumber__ + 1 WHERE a.id = :accountId RETURNING a.id as id)
DQL does not support the RETURNING clause, so you need to use native SQL. You will also have to create a result set mapping.
NOTE: I don't know the actual names of your table and columns, but assuming they are named the same as your entity and properties, this will work:
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addScalarResult('jobReferenceNumber', 'jobReferenceNumber');
$sql = "
UPDATE account a
SET a.jobReferenceNumber = a.jobReferenceNumber + 1
WHERE a.id = :accountId
RETURNING a.jobReferenceNumber
";
$query = $this->entityManager->createNativeQuery($sql, $rsm);
$query->setParameter('accountId', $account->getId());
$total = $query->getSingleScalarResult();
You may need to correct the table and column names in my example. When using native SQL, you have to use the actual names in the database, not the names of entity and properties. Also, remember that postgres converts all object names to upper case unless they are quoted.
thanks for the insight :) this is working now
Heres my updated code :
Above the class i use the ResultSetMapping
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping();
$rsm->addScalarResult('ref_inc_num', 'ref_inc_num');
$sql = "
UPDATE ja_clients
SET ref_inc_num = ref_inc_num + 1
WHERE id = :clientId
RETURNING ref_inc_num
";
$query = $this->entityManager->createNativeQuery($sql, $rsm);
$query->setParameter('clientId', $account->getId());
$refNum = $query->getSingleScalarResult();
I am having problems achieving the query to select data from a table in the db after a defined value has been met.
My code to do this is:
$fi = 'first_segment'
$im = popo.jpg
$sqls = "SELECT * FROM $fi,news_pictures
WHERE $fi.pi_id = news_pictures.pi_id
AND news_pictures.i_name = '$im'
GROUP BY news_pictures.id DESC";
I wasn't able to achieve the result with that query.
Basically, I want the query to confirm if news_pictures.i_name = '$im' and if true, return starts from the value of $im followed by other data in the table depending on news_pictures.id DESC.
The sample data and output:
Table news_pictures:
id i_name
-- ------
1 coco.jpg
2 lolo.jpg
3 popo.jpg
4 dodo.jpg
Since $im = popo.jpg, I want my query to display all values starting from popo.jpg with id DESC, i.e. popo.jpg, lolo.jpg, coco.jpg.
I got to solve the question with the help of a friend.
$fsqls = "SELECT * FROM $fi,news_pictures WHERE $fi.pi_id = news_pictures.pi_id AND news_pictures.i_name = '$im' GROUP BY news_pictures.id";
$rres = mysqli_query($connection, $fsqls) or print(mysqli_error($connection));
while($row = mysqli_fetch_assoc($rres))
{
$rnm = $row["id"];
}
$sqls = "SELECT * FROM news_pictures WHERE news_pictures.id <= $rnm ORDER BY news_pictures.id DESC";
I am trying yto select a column from my DB where the stockid is equal to the inputted stockid from the user. This is my code below:
$stockid = $_POST['item'];
//get the current balance of the selected item
$sqlbal = "SELECT * FROM db.nonperi where nonperi.stockid = '$stockid'";
$resultbal = $conn-> query($sqlbal);
if ($resultbal-> num_rows > 0)
{
while ($row = $resultbal -> fetch_assoc())
{
$currbal = $row['bal'];
}
}
I know that the code is correct, however, upon checking in DB, the stockid is equivalent to '2015123' but the $stockid that was posted in this page for this code is '02015123'. That is why it returns nothing.
Is there any code/way to force sql to see them as the same/equal? I appreciate any help about this.
You are passing the stockid as a string (but want it to behave like an integer).
Try
$stockid = intval($_POST['item']);
$sqlbal = "SELECT * FROM db.nonperi where nonperi.stockid = $stockid";
(That also secures your code to prevent SQL injection)
You can trim leading 0 (zeros) to check the stockId.
SELECT TRIM(LEADING '0' FROM '02454545')
You command should be:
"SELECT * FROM db.nonperi where nonperi.stockid = TRIM(LEADING '0' FROM '$stockid')";
$dt = mysql_query("SELECT * FROM `member_territory` mt LEFT JOIN `drug_territory` dt ON mt.mt_ter = dt.t_id");
while($t = mysql_fetch_array($dt)) {
$total +=($t['t_reward']* $t['mt_lev'])*150;
mysql_query("UPDATE `members` SET
`drug_income` = '".$total."',
`drug_incometotal` = `drug_incometotal` + '".$total."',
`wallet` = `wallet` + '".$total."'
WHERE `playerid` = '".$t['mt_playerid']."'");
}
So here is my code rather self explainingtary $total when inserted into drug_income that is correct but when ever it is inserted into drug_incometotal or wallet its incorrect.
im not sure why and i have tried everything to my knowledge to pull my head around it!!.
Any ideas why i am getting this incorrect result ( as i say drug_income is correct) only when i try to '+' it to something in the data base it returns an incorrect result.
i dont want to increment just once after the loop... – user3740302 1 min ago
Okay then. So you should probably move your UPDATE query outside of the loop, right?
You may try this modified update query
mysql_query("UPDATE `members` SET drug_income = ".$total.", drug_incometotal = drug_incometotal + ".$total.", wallet = wallet + ".$total." WHERE `playerid` = '".$t['mt_playerid']."'");
It may resolve your problem..
Currently, I have the following PHP code loaded every time the page is refreshed. I am trying to update the views column +1 every time the page is loaded. To do this, I first retrive the previous views value from the table, then run another query to add + to that number. The problem that is occurring is every time I refresh the page, The code somehow adds two instead of 1. So instead of the $viewsA variable increasing by +1, it is increasing by +2.
$query = mysql_query("SELECT * FROM Games WHERE pagename = '$game' ");
WHILE($datarows = mysql_fetch_array($query)):
$title = $datarows['title'];
$description = $datarows['desc'];
$img_url = $datarows['img'];
$cat = $datarows['cat'];
$pagename = $datarows['page'];
$rating = $datarows['rat'];
$viewsA = $datarows['view_count'];
$gameid = $datarows['id'];
endwhile;
$updateviews = $viewsA +1;
mysql_query("UPDATE `trainw_games`.`Games` SET `view_count` = '$updateviews' WHERE `Games`.`id` = $gameid;");
What do I need to change to make it only add +1 to the views column?
I don't think that a while loop is appropriate for this problem. I would recommend to echo $viewsA . '-' . $updateviews; to see what the value is before and after the add.
But, why not just run a single UPDATE statement?
UPDATE Games SET view_count = view_count + 1 WHERE Games.id = $gameid
Of course, you should stop using mysql_ functions and use either MySQLi or PDO:
$stmt = $mysqli->prepare("UPDATE Games SET view_count = view_count + 1 WHERE Games.id = ?");
$stmt->bind_param($gameid);
$stmt->execute();
$stmt->close();
Do you have multiple rows in your database? If yes, it maybe caused by overriding the previous value.
For example:-
If first row the view_count is 1.
While the second row view_count is 2.
that overrides the the first row with 2 + 1 = 3
Which makes you thought increased by 2?
UPDATE 1:
Ok, try this, put this
$updateviews1 = $viewsA + 1;
if ($viewsA < $updateviews1) { //execute the viewsA + 1 }