Update a single record in database CakePHP - mysql

I am trying to update a single record of the database with the function "updateAll", and filtering by a single "id".
$this->Factura->updateAll(
array(
'Factura.I_COBRADO' => $factura['Factura']['I_TOTAL'],
'Factura.L_COBRADA' => 1,
'Factura.FH_COBRO' => date('Y-m-d H:i:s'),
'Factura.S_FORMAPAGO' => 'tarjeta',
'Factura.FK_FORMAPAGOCOBRO' => 41
),
array(
'Factura.PK_FACTURA' => $factura['Factura']['PK_FACTURA'])
)
But I get this error:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '15:10:55, Factura.S_FORMAPAGO = tarjeta, Factura.FK_FORMAPAGOCOBRO = 41 ' at line 1
SQL Query: UPDATE itramit_daily_desarrollo.facturas AS Factura LEFT JOIN itramit_daily_desarrollo.expedientes AS Expediente ON (Factura.FK_EXPEDIENTE = Expediente.PK_EXPEDIENTE) LEFT JOIN itramit_daily_desarrollo.expedientes AS ExpedienteFactura ON (Factura.FK_EXPEDIENTE = ExpedienteFactura.PK_EXPEDIENTE) LEFT JOIN itramit_daily_desarrollo.municipios AS Municipio ON (Factura.FK_MUNICIPIO = Municipio.PK_MUNICIPIO) LEFT JOIN itramit_daily_desarrollo.valoraciones AS Valoracione ON (Factura.FK_VALORACION = Valoracione.PK_VALORACION) LEFT JOIN itramit_daily_desarrollo.liquidaciones AS Liquidacione ON (Factura.FK_LIQUIDACION = Liquidacione.PK_LIQUIDACION) LEFT JOIN itramit_daily_desarrollo.formaspagoscobros AS Formaspagoscobro ON (Factura.FK_FORMAPAGOCOBRO = Formaspagoscobro.PK_FORMAPAGOCOBRO) SET Factura.I_COBRADO = 165.00, Factura.L_COBRADA = 1, Factura.FH_COBRO = 2021-08-16 15:10:55, Factura.S_FORMAPAGO = tarjeta, Factura.FK_FORMAPAGOCOBRO = 41 WHERE Factura.PK_FACTURA = 166569

Running your query through MySQL Workbench, I see that
Factura.FH_COBRO = 2021-08-16 15:10:55
is the cause of the syntax error. It appears that CakePHP does not add quotes around the data value.
Try:
'Factura.FH_COBRO' => "'" + date('Y-m-d H:i:s') + "'",
'Factura.S_FORMAPAGO' => "'tarjeta'",

Related

TypeORM-NestJs Join on Json column

join two mysql tables using typeorm-NestJs
where table 1(t1) is normal table
& table 2(t2) has a column which containts JSON data
now I need to join them based on t1.id == t2.column_name.id
but I am getting error on that query
query I am using :-
const results = await this.connection.createQueryBuilder(ABCEntity,'t1')
.innerJoinAndMapMany('t1.Id',xyzEntity,'t2','t1.Id = t2.column_name.$.Id')
.where('t1.Id = :Id',{Id: id})
.getMany()
.catch(err => console.log(err));
Error I am getting :-
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 '.Id WHERE `t1`.`Id` = 'b6D812aF-9e22-4a5a-a292-6rc5021bfv0a'' at line 1",
sqlState: '42000',
what worked for me was, everything in backticks
for eg : `t1.Id = t2.column_name->'$.Id'
const results = await this.connection.createQueryBuilder(ABCEntity,'t1')
.innerJoinAndMapMany('t1.Id',xyzEntity,'t2',`t1.Id = t2.column_name->'$.Id'`)
.where('t1.Id = :Id',{Id: id})
.getMany()
.catch(err => console.log(err));

Whats wrong with my query, should i use WHERE?

So, what am i doing wrong?
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type)
VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered');
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: SQLSTATE[HY000]: General error: 1111 Invalid use
of group function
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered') WHERE art_nr = '$art_nr';
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 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 art_nr = 'S2Bygel'; UPDATE purchase_orderlist SET
list' at line 2
UPDATE
This was my first query. With Params:
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id'],
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES (:art_nr, :article, :balance, :list_type)
ON DUPLICATE KEY UPDATE balance = balance + VALUES(:quantity_ordered) WHERE art_nr = :art_nr;
UPDATE table2 SET list = 'History' WHERE id = :id";
The problem with this query is that im running two querys at the same time. and then i will get this error:
Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
SUCCESS
I had to use prepared statements and separate my two querys:
//SECURITY
$params_array= array(
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1
(art_nr, article, balance, list_type)
VALUES (:art_nr, :article, :quantity_ordered, :list_type)
ON DUPLICATE KEY UPDATE
art_nr = art_nr, article = article, balance = balance + :quantity_ordered, list_type = list_type";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id']
);
//QUERY
$query = "UPDATE table2 SET list = 'History' WHERE id = :id";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
echo "success";
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
You just want to add the value of $quantity_ordered to balance for the row? Then you don't need the sum() aggregation function. Just the + operator is enough.
But it seems like you're doing this in a host language like PHP. You should urgently learn to use parameterized queries! Do not use string concatenation (or interpolation) to get values in a query. That's error prone and may allow SQL injection attacks against your application.

Error trying to turn raw sql into laravel query builder

I am trying to turn this very long raw sql into laravel query builder and encounter an error.
This is the original raw sql
sql = "select d.doc_Code,d.seq,p.seq2,d.product_code,d.name_t,d.dwg_file,p.book,concat(p.book,'-',p.seq) as job_book,h.sale_code,h.sale_name,h.ref_code,h.ref_name,h.priority,p.code,p.in_time,wt_date,p.job_status,d.status,DATEDIFF(now(),p.in_time) as gdays,DATEDIFF(h.due_date,now()) as gdue_days,h.due_date,h.start_date as start_datex from jt_p as p inner join jt_d as d on (p.doc_code=d.doc_code and p.book=d.book and p.seq=d.seq and p.in_time is not null and p.wt_date is null and p.job_status not in('Z','C') and p.code<>'M' and d.status <>'C') inner join jt_h as h on(h.doc_code =p.doc_code and h.book=p.book)"
Here is the laravel query builder:
$jt_p = DB::table('jt_p')
->join('jt_d', function($join){
$join->on('jt_p.doc_code', '=', 'jt_d.doc_code');
$join->on('jt_p.book','=','jt_d.book');
$join->on('jt_p.seq','=','jt_d.seq');
})
->where('jt_p.in_time','!=','')
->where('jt_p.wt_time','=','')
->where('jt_p.job_status',DB::raw('not in ("Z","C")'))
->where('jt_p.code','!=','M')
->where('jt_d.status','!=','C')
->join('jt_h', function($join){
$join->on('jt_h.doc_code', '=', 'jt_p.doc_code');
$join->on('jt_p.book','=','jt_h.book');
})
->select('jt_d.doc_code','jt_d.seq','jt_p.seq2','jt_d.product_code','jt_d.name_t','jt_d.dwg_file','jt_p.book',
'jt_h.sale_code','jt_h.sale_name','jt_h.ref_code','jt_h.ref_name','jt_h.priority','jt_p.code','jt_p.in_time','jt_p.wt_time',
'jt_p.job_status','jt_d.status',DB::raw("DATEDIFF(now(),jt_p.in_time) as gdays"),
DB::raw("DATEDIFF(jt_h.due_date,now()) as gdue_days"),
'jt_h.due_date','jt_h.start_date as start_datex')
->get();
return $jt_p;
This is the error message:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 'not in ("Z","C") and `jt_p`.`code` != ? and `jt_d`.`status` != ?' at line 1 (SQL: select `jt_d`.`doc_code`, `jt_d`.`seq`, `jt_p`.`seq2`, `jt_d`.`product_code`, `jt_d`.`name_t`, `jt_d`.`dwg_file`, `jt_p`.`book`, `jt_h`.`sale_code`, `jt_h`.`sale_name`, `jt_h`.`ref_code`, `jt_h`.`ref_name`, `jt_h`.`priority`, `jt_p`.`code`, `jt_p`.`in_time`, `jt_p`.`wt_time`, `jt_p`.`job_status`, `jt_d`.`status`, DATEDIFF(now(),jt_p.in_time) as gdays, DATEDIFF(jt_h.due_date,now()) as gdue_days, `jt_h`.`due_date`, `jt_h`.`start_date` as `start_datex` from `jt_p` inner join `jt_d` on `jt_p`.`doc_code` = `jt_d`.`doc_code` and `jt_p`.`book` = `jt_d`.`book` and `jt_p`.`seq` = `jt_d`.`seq` inner join `jt_h` on `jt_h`.`doc_code` = `jt_p`.`doc_code` and `jt_p`.`book` = `jt_h`.`book` where `jt_p`.`in_time` != and `jt_p`.`wt_time` = and `jt_p`.`job_status` = not in ("Z","C") and `jt_p`.`code` != M and `jt_d`.`status` != C)
Change this line of code
->where('jt_p.job_status',DB::raw('not in ("Z","C")'))
to
->whereNotIn('jt_p.job_status',["Z","C"])
You need also to use IsNull IsNotNull
$jt_p = DB::table('jt_p')
->join('jt_d', function($join){
$join->on('jt_p.doc_code', '=', 'jt_d.doc_code');
$join->on('jt_p.book','=','jt_d.book');
$join->on('jt_p.seq','=','jt_d.seq');
})
->whereNotNull('jt_p.in_time')
->whereNull('jt_p.wt_time')
->whereNotIn('jt_p.job_status',["Z","C"])
->where('jt_p.code','!=','M')
->where('jt_d.status','!=','C')
->join('jt_h', function($join){
$join->on('jt_h.doc_code', '=', 'jt_p.doc_code');
$join->on('jt_p.book','=','jt_h.book');
})
->select('jt_d.doc_code','jt_d.seq','jt_p.seq2','jt_d.product_code','jt_d.name_t','jt_d.dwg_file','jt_p.book',
'jt_h.sale_code','jt_h.sale_name','jt_h.ref_code','jt_h.ref_name','jt_h.priority','jt_p.code','jt_p.in_time','jt_p.wt_time',
'jt_p.job_status','jt_d.status',DB::raw("DATEDIFF(now(),jt_p.in_time) as gdays"),
DB::raw("DATEDIFF(jt_h.due_date,now()) as gdue_days"),
'jt_h.due_date','jt_h.start_date as start_datex')
->get();
return $jt_p;

wordpress plugin sql synatax

problem in Mashable Slider Clone plugin when uload it in server
WordPress database error: [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 ')' at line 3] SELECT * FROM wp_mash_fields WHERE docid IN()
code for this is
$sql = "SELECT *
FROM $this->flds
WHERE docid IN(".implode(',' , array_keys($r)).")";
$r2 = $this->db->get_results($sql, ARRAY_A);
WordPress database error: [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 'LIMIT 0,999' at line 3] SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_mash_documents.* FROM wp_mash_documents WHERE wp_mash_documents.type='image' ORDER BY wp_mash_documents. LIMIT 0,999;
code for this is
function get($type, $page = 0, $limit = 10, $sort = 'modify_time', $ord = 'ASC', $rel = null, $dorder = false, $s = null)
{
$ll = $page * $limit;
$docs = $this->docs;
$flds = $this->flds;
$rels = $this->rels;
$inner = array();
$where = array();
$order = '';
// get ids
$sql = "SELECT SQL_CALC_FOUND_ROWS DISTINCT $docs.*".($dorder? ",$rels.dorder" : "")." FROM $docs";
switch ($sort) {
case "title":
$inner[$flds] = array("$docs.id", "$flds.docid");
$where["$flds.name"] = "='title'";
$order = "$flds.value_text $ord";
if (isset($s)) {
$where["MATCH ($flds.value_text)"] = " AGAINST ('$s')";
}
Given your error message:
ORDER BY wp_mash_documents. LIMIT 0,999;
^---missing field name

MYSql - Using correlated subquery in Zend Db

I'm trying to construct a working MySql query with a correlated subquery in zend_db_select (ZF 1.12) to use that in Zend_Paginator_Adapter. The working query is as follows:
SELECT f.*, (SELECT (COUNT(p.post_id) - 1)
FROM `forum_topic_posts` AS p WHERE f.topic_id = p.topic_id) AS post_count
FROM `forum_topics` AS f WHERE f.forum_id = '2293'
ORDER BY post_count DESC, last_update DESC
So i worked out:
$subquery = $db->select()
->from(array('p' => 'forum_topic_posts'), 'COUNT(*)')
->where('p.topic_id = f.topic_id');
$this->sql = $db->select()
->from(array('f' => 'forum_topics'), array('*', $subquery . ' as post_count'))
->where('forum_id=?', $forumId, Zend_Db::PARAM_INT)
->order('post_count ' . $orderDirection);
But Zend stops with the following exception when executing the query:
Zend_Db_Statement_Mysqli_Exception: Mysqli prepare error: 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 'SELECT COUNT(*) FROM forum_topic_posts AS p WHERE (p.topic_id = f.to' at line 1
How could i get the subquery to work?
Here is the query written using the Zend_Db OO interface.
The key was mostly using some Zend_Db_Expr objects for the subquery and COUNT function.
$ss = $db->select()
->from(array('p' => 'forum_topic_posts'),
new Zend_Db_Expr('COUNT(p.post_id) - 1'))
->where('f.topic_id = p.topic_id');
$s = $db->select()
->from(array('f' => 'forum_topics'),
array('f.*', 'post_count' => new Zend_Db_Expr('(' . $ss . ')')))
->where('f.forum_id = ?', 2293)
->order('post_count DESC, last_update DESC');
echo $s;
// SELECT `f`.*, SELECT COUNT(p.post_id) - 1 FROM `forum_topic_posts` AS `p` WHERE (f.topic_id = p.topic_id) AS `post_count` FROM `forum_topics` AS `f` WHERE (f.forum_id = 2293) ORDER BY `post_count DESC, last_update` DESC