How can I add to an existing value in sql table - sql

How can i add a value to an existing value in SQL example a value 4 in a column how can i add 2 to it to make it 6 not to update to 2 but to add the previous value and the new value to together here is my class php file
<?php
class data
{
public $d_count;
public $id;
private $conn;
private $table_name;
public function __construct($db)
{
$this->conn = $db;
$this->table_name= "tbl_data";
}
public function updateCount()
{
// $query = "UPDATE tbl_data SET d_count = ?, date_updated = ? WHERE id = ?";
$query = "UPDATE tbl_data SET d_count '+1' = ?, date_updated = ? WHERE id = ?";
$obj = $this->conn->prepare($query);
$this->d_count = htmlspecialchars(strip_tags($this->d_count));
$this->date_updated = htmlspecialchars(strip_tags($this->date_updated));
$this->id = htmlspecialchars(strip_tags($this->id));
$obj->bind_param("sss", $this->d_count, $this->date_updated, $this->id);
if ($obj->execute()) {
return true;
}
return false;
}
}
The line I commented out is what i used to test the code and it works fine but now i need to add the old value + new value together here is the code am using to update the table
<?php
$data = new data($connection);
if($_SERVER['REQUEST_METHOD'] === "POST"){
$newDCount = json_decode(file_get_contents("php://input"));
if(!empty($newDCount->d_count))
$data->id= $newDCount->id;
$data->d_count = $newDCount->d_count;
$data->date_updated = date('Y-m-d H:i:s', time());
if($apiata->updateCount()){
http_response_code(200);
echo json_encode(array(
"status" => 200,
"message" => "Success"
));
}
else
{
http_response_code(200);
echo json_encode(array(
"status" => 500,
"message" => "Failed"
));
}
}

To update the d_count to add to the existing d_count value, the query should look like:
$sql = 'UPDATE catalog SET d_count = d_count + ?, date_updated = ? WHERE id = ?';
The other handling should be ok as-is.

Related

TYPO3 9.5 Extbase Query for UidArray

I´ve got the following SQL-Query
$uidArray = explode(",", $uids);
foreach ($uidArray as $uid) {
$dynamicUid[] = '`uid` LIKE \''.$uid.'\'';
}
$query = $this->createQuery();
$query->statement("SELECT * FROM `tx_myextension_domain_model_thi` WHERE ".implode($dynamicUid, " OR "));
return $query->execute();
This works fine but I want to have it like this:
$uidArray = explode(",", $uids);
$query = $this->createQuery();
foreach ($uidArray as $key => $value) {
$constraints[] = $query->equals('uid', $value);
}
return $query->matching(
$query->logicalAnd($constraints)
)->execute();
Here I get the following Output with the Query Parser :
'SELECT `tx_myextension_domain_model_thi`.* FROM `tx_myextension_domain_model_thi`
`tx_myextension_domain_model_thi`
WHERE ((`tx_myextension_domain_model_thi`.`uid` = :dcValue1) AND
(`tx_myextension_domain_model_thi`.`uid` = :dcValue2)) AND
(`tx_myextension_domain_model_thi`.`sys_language_uid` IN (0, -1)) AND
(`tx_myextension_domain_model_thi`.`pid` = 0) AND
((`tx_myextension_domain_model_thi`.`deleted` = 0) AND (
`tx_myextension_domain_model_thi`.`t3ver_state` <= 0) AND
(`tx_myextension_domain_model_thi`.`pid` <> -1) AND
(`tx_myextension_domain_model_thi`.`hidden` = 0) AND
(`tx_myextension_domain_model_thi`.`starttime` <= 1607084460) AND
((`tx_myextension_domain_model_thi`.`endtime` = 0)
OR (`tx_myextension_domain_model_thi`.`endtime` > 1607084460)))'
And the Uids as dcValue-Array.
dcValue1 => '1' (1 chars)
dcValue2 => '2' (1 chars)
Maybe someone can help me to rewrite this, because unfortunately I can't get any further!
Thanks :)
Did you try the in operator?
public function yourFunctionName($uid)
{
$query = $this->createQuery();
$query->in('uid', $uidArray);
return $query->execute();
}
Assuming that your array looks like this:
$uidArray = [
0 = '34',
1 = '15',
3 = '88'
]
EDIT
If you do not care about where your objects are stored then you can do the following.
public function yourFunctionName($uid)
{
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(FALSE);
$query->matching(
$query->in('uid', $uidArray)
);
return $query->execute()];
}
Which is going to ignore the pid in the query

Yii2 Update the entry if it exists

Item $title defined earlier. I want what if found $find_title, update it with all fields from $title. Otherwise, create a new object
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
$title->id = $find_title->id;
$title->save();
} else {
$title->save();
}
It worked in the laravel.
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
$id = $title->id;
$find_title->attributes = $title->attributes;
$find_title->id = $id;
$find_title->save();
} else {
$title->save();
}
Here you assign all attributes of $title to $find_title, restore id, and then save;

ignore where statement if parameter is null in doctrine

Hi i have a problem in QueryByilder in Doctrine. i wrote a Query that has 2 parameter and they affect in where statement. i want to ignore where statement if the related parameter was null. for example if $play = 3 and $theater = null the query must return all tickets with play 3 and whatever theater
this is my code:
public function getAllSearchedTickets($play,$teater){
return $this->getEntityManager()->createQuery('
select s from mtadminBundle:ReserveLocation s
join s.reserve a
join a.sance b
where a.acceptCode != 0
and b.play = :play
and b.teater = :teater')
->setParameters(array('play'=>$play,'teater'=>$teater))->getResult();
}
thank you.
You should use the QueryBuilder for this, to do it more efficiently, I'll show you how you do yours and then the same with the QueryBuilder as example:
Yours:
public function getAllSearchedTickets($play,$teater){
$query = 'select s from mtadminBundle:ReserveLocation s'.
'join s.reserve a'.
'join a.sance b'.
'where a.acceptCode != 0');
$paramArray = array();
if( $play ) {
$query .= ' and b.play = :play';
$paramArray['play'] = $play;
}
if( $teater ) {
$query .= ' and b.teater = :teater';
$paramArray['teater '] = $teater;
}
return $this->getEntityManager()->createQuery($query)
->setParameters($paramArray)->getResult();
}
QueryBuilder:
public function getAllSearchedTickets($play,$teater){
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->select('s')
->from('mtadminBundle:ReserveLocation', 's')
->join('s.reserve', 'a')
->join('a.sance', 'b')
->where('a.acceptCode != 0');
if( $play ) {
$queryBuilder->andWhere('b.play = :play');
$queryBuilder->setParameter('play', $play);
}
if( $teater ) {
$queryBuilder->andWhere('b.teater = :teater');
$queryBuilder->setParameter('teater', $teater);
}
return $queryBuilder->getResult();
}

Get raw sql from Phalcon query builder

Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?
$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
->from(…)
->where(…);
$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);
$intermediate = $queryBuilder->getQuery()->parse();
$dialect = DI::getDefault()->get('db')->getDialect();
$sql = $dialect->select($intermediate);
Edit: As of 2.0.3 you can do it super simple, see comment for full details:
$modelsManager->createBuilder()
->from('Some\Robots')
->getQuery()
->getSql()
you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html
According to documentation you can get this way the resulting sql query.
Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements
$db = Phalcon\DI::getDefault()->getDb();
$sql = $db->getSQLStatement();
$vars = $db->getSQLVariables();
if ($vars) {
$keys = array();
$values = array();
foreach ($vars as $placeHolder=>$var) {
// fill array of placeholders
if (is_string($placeHolder)) {
$keys[] = '/:'.ltrim($placeHolder, ':').'/';
} else {
$keys[] = '/[?]/';
}
// fill array of values
// It makes sense to use RawValue only in INSERT and UPDATE queries and only as values
// in all other cases it will be inserted as a quoted string
if ((strpos($sql, 'INSERT') === 0 || strpos($sql, 'UPDATE') === 0) && $var instanceof \Phalcon\Db\RawValue) {
$var = $var->getValue();
} elseif (is_null($var)) {
$var = 'NULL';
} elseif (is_numeric($var)) {
$var = $var;
} else {
$var = '"'.$var.'"';
}
$values[] = $var;
}
$sql = preg_replace($keys, $values, $sql, 1);
}
More you can read there
The following is the common solution:
$result = $modelsManager->createBuilder()
->from(Foo::class)
->where('slug = :bar:', ['bar' => "some-slug"])
->getQuery()
->getSql();
But you might not expect to see the query without its values, like in:
die(print_r($result, true));
Array
(
[sql] => SELECT `foo`.`id`, `foo`.`slug` FROM `foo` WHERE `foo`.`slug` = :bar
[bind] => Array
(
[bar] => some-slug
)
[bindTypes] =>
)
So, this simple code might be useful:
public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
{
$data = $builder->getQuery()->getSql();
['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;
$finalSql = $sql;
foreach ($binds as $name => $value) {
$formattedValue = $value;
if (\is_object($value)) {
$formattedValue = (string)$value;
}
if (\is_string($formattedValue)) {
$formattedValue = sprintf("'%s'", $formattedValue);
}
$finalSql = str_replace(":$name", $formattedValue, $finalSql);
}
return $finalSql;
}
If you're using query builder then like given below then getPhql function can serve the purpose as per phalcon 3.4.4 version.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…)->getQuery();
$queryBuilder->getPhql();
if (!function_exists("getParsedBuilderQuery")) {
/**
* #param \Phalcon\Mvc\Model\Query\BuilderInterface $builder
*
* #return null|string|string[]
*/
function getParsedBuilderQuery (\Phalcon\Mvc\Model\Query\BuilderInterface $builder) {
$dialect = Phalcon\Di::getDefault()->get('db')->getDialect();
$sql = $dialect->select($builder->getQuery()->parse());
foreach ($builder->getQuery()->getBindParams() as $key => $value) {
// For strings work fine. You can add other types below
$sql = preg_replace("/:?\s?($key)\s?:?/","'$value'",$sql);
}
return $sql;
}
}
Simple function that im using for debugging.

PHP PDO dynamically updating db table with multiple records to a specific user ID

/* Newbie need some help; I am creating a class to auto update my apps db record when instructed to, but I am consistently getting this message below, and for the heck of it, I just not seeing what I am doing wrong. Can someone please look at my codes for me? Thank you.
Warning: PDOStatement::bindParam() expects at least 2 parameters, 1 given in……..on line 331; that where the "else if(is_string($val)){" is located.
*/
// vars given
// DBDriver: MySQL
$myTable = 'seeYou';
$loginDate = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
$date = #date('m/d/Y \a\\t h:i a');
$_id =1;
// data array
$idata = array("last_logged_in"=>$loginDate,
"login_date"=>$date,
"ip_addr"=>$ip
);
class name
{
///------------ other methods here---------///
/**
*--------------------------------------------
* Method - PDO: SET FIELD VALUE PLACEHOLDER
*--------------------------------------------
* #return fields with prefix as placeholder
*/
protected function set_fieldValPlaceHolders(array $data)
{
$set = '';
foreach($data as $field => $value)
{
$set .= $field .'= :'.$field . ',';
}
// remove the last comma
$set = substr($set, 0, -1);
return $set;
}
public function save($data=NULL, $_id = NULL, $rows= NULL, $dbTable= NULL)
{
//----------------- some other codes goes here ----------------//
$id = (int)$_id;
// update row with a specific id
if (isset($id) !== NULL && $rows === NULL)
{
$set = $this->set_fieldValPlaceHolders($data);
$sql = "UPDATE {$dbTable} SET {$set} WHERE user_id = :uid";
try
{
// Build the database statement
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindValue(':uid',$id, PDO::PARAM_INT);
foreach ($data as $field => $val)
{
if(is_int($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_INT');
}
else if(is_string($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_STR');
}
else if(is_bool($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_BOOL');
}
else if(is_null($val)){
$_stmt->bindValue(':'.$field.'\', '.$val="null".', PDO::PARAM_NULL');
}
else {
$_stmt->bindValue(':'.$field.'\', '.$val.', NULL');
}
$result = $_stmt->execute();
$num = $_stmt->rowCount();
}
}
catch(PDOException $e)
{
die('Error! The process failed while updating your record. <br /> Line #'.__LINE__ .' '.$e);
}
if ($result === true)
{
return true;
}
}
Check your bindValue calls: You give 1 parameter (a long string). It needs at least two. Check all the '
for example, it should be:
$_stmt->bindValue(':'.$field, $val, PDO::PARAM_INT);