PHP update multiple tables in one statement error - php

I have tried many solutions that I have found on stackoverflow but keep getting the same error when trying to update my tables within the one statement.
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 'WHERE docID=7' at line 2
Code:
<?php
if(isset($_POST['btn-revActivate']))
{
try
{
$database = new Database();
$db = $database->dbConnection();
$conn = $db;
$stmt=$conn->prepare("UPDATE tbl_revisions, tbl_documents SET revStatus='Active', docStatus='Draft'
WHERE revID=$rid AND docID=$docID ");
$stmt->bindparam("revStatus",$revStatus);
$stmt->bindparam(":id",$rid);
$stmt->bindparam("docStatus",$docStatus);
$stmt->bindparam(":docID",$docID);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
?>
Can someone please help as I don't know what is wrong with this statement.
Thanks.

You can't update multiple tables in one statement.if you want to update then you can use a transaction to make sure that two UPDATE statements are treated atomically.
BEGIN TRANSACTION;
UPDATE tbl_revisions
SET revStatus='Active', docStatus='Draft'
WHERE revID=$rid AND docID=$docID ';
UPDATE tbl_documents
SET revStatus='Active', docStatus='Draft'
WHERE revID=$rid AND docID=$docID ';
COMMIT;
for more information
https://dev.mysql.com/doc/refman/5.7/en/commit.html

Related

i get sql syntax error and dint match any of suggested answer

Error: 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 ''dashboards' (employ_id,system_id,on-time,off-time,is_active) values ('Array' at line 1
public function admin_dashboard($id=null) {
$this->loadModel('Employ','System');
if ($this->request->is('post')) {
//debug($this->request->data);exit;
$employId = $this->request->data['Dashboard']['employ_id'];
$systemId = $this->request->data['Dashboard']['system_id'];
$logon = $this->request->data['Dashboard']['on-time'] = date("Y-m-d H:i:s");
$logout = $this->request->data['Dashboard']['off-time'] = date("Y-m-d H:i:s");
$active = $this->request->data['Dashboard']['is_active'];
//$date=date("Y-m-d H:i:s");
for($i=0;$i<count ($systemId);$i++){
$this->System->query("insert into 'dashboards' (employ_id,system_id,on-time,off-time,is_active) values ('$employId','$systemId[$i]','$logon','$logout','$active')");
//$var_dump($date);
}
$this->Session->setFlash(__('The query has been saved.'));
return $this->redirect(array('action' => 'admin_dashboard'));
}/* else {
$this->Session->setFlash(__('The query could not be saved. Please, try again.'));
}*/
$employs = $this->Employ->find('list');
$systems = $this->System->find('list');
$this->set(compact('employs','systems'));
}
The MySQL identifier quote character is the backtick
The first error in the question is because the quote character of MySQL is the backtick not a single quote.
i.e. valid:
mysql> SELECT * FROM `select` WHERE `select`.id > 100;
Invalid:
mysql> SELECT * FROM 'select' WHERE 'select'.id > 100;
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 ''select' WHERE 'select'.id > 100' at line 1
mysql>
There are literally thousands of similar questions on stack overflow, as it's a common mistake.
There is no need to use query
However that's not the biggest problem/mistake in the question code. Model::query is designed/expected to be used for:
SQL calls that you can’t or don’t want to make via other model methods
Inserting data into the db does not fall into that category; Effectively it should be used as a last resort (generally speaking it is very rare to need to use this method).
Something similar to this is all that's required:
$this->loadModel('Dashboard');
$data = [];
foreach ($this->request->data['Dashboard']['system_id'] as $systemId) {
$row = $this->request->data['Dashboard'];
$row['system_id'] = $systemId;
$data[] = $row;
}
$this->Dashboard->saveMany($data);
saveMany is one of the standard ways to save data, and the most appropriate given the info in the question.
Note that if the logic is any more than a few lines of code it should not be in a controller action at all, and moved to the model instead e.g.:
// in controller
$this->Dashboard->myMethod($data);
// in the Dashboard class:
public function myMethod($input)
{
... whatever is necessary ...
return $this->saveMany($data);
}

MySQL/MariaDB transaction access violation 1064

I'm having a bit of trouble with a transaction query. I have 2 tables,
"subjects" and linking table call "tutorsubjects". I am using a MariaDB version 10.0.21. I have created the following query but I keep getting a "Syntax error or access violation: 1064" error.
public function addSubject($values){
try {
$temp = $this->db->query("
BEGIN;
INSERT INTO subjects
(subject_code, subject_name, subject_grade, subject_description, subject_category)
VALUES (:subject_code, :subject_name, :subject_grade, :subject_description, :subject_category);
SET #last_id = LAST_INSERT_ID();
INSERT INTO tutorsubject
(tutor_id , subject_id)
VALUES (:tutor_id, #last_id);
COMMIT;",$values);
return $temp;
} catch (DBException $e) {
echo "Error:<br/>" . $e->getMessage();
return null;
} catch (Exception $e) {
echo "Error:<br/>" . $e->getMessage();
return null;
}
}
The following is the values that are parsed through to the query
$array = array("subject_code" => $code,
"subject_name" => $subject_name,
"subject_grade" => $grade,
"subject_description" => $subject_description,
"subject_category" => $subject_category,
"tutor_id"=>$selecttutor);
I get the following 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 ''reach'.'subjects' ('subject_code', 'subject_name', 'subject_grade', 'subject_de' at line 1
Raw SQL : INSERT INTO 'reach'.'subjects' ('subject_code', 'subject_name', 'subject_grade', 'subject_description', 'subject_category') VALUES (:subject_code,:subject_name,:subject_grade,:subject_description,:subject_category);
My issue is that when I run this query in phpMyAdmin it completes without any issues. I am using a PDO MySQL class found here as the foundation for my DB interactions. I am starting to think that perhaps the class does not directly support transactions?
Any thoughts would be greatly appreciated.
Try having PHP do the work + using PDO transaction methods, values part not tested so you need to make sure its correct:
$this->db->beginTransaction();
$this->db->query("INSERT INTO subjects
(subject_code, subject_name, subject_grade, subject_description, subject_category)
VALUES (:subject_code, :subject_name, :subject_grade, :subject_description, :subject_category)", $values);
$values['last_id'] = $this->db->lastInsertId();
if (empty($values['last_id'])) {
$this->db->rollBack();
} else {
$this->db->query("INSERT INTO tutorsubject
(tutor_id , subject_id)
VALUES (:tutor_id, :last_id)", $values);
$this->db->commit();
}
You should try leaving the COMMIT and BEGIN queries alone.
Try:
// start the transaction
$this->db->query("BEGIN;");
//rest of your queries with db->query() go here
$this->db->query("INSERT INTO subjects
(subject_code, subject_name, subject_grade, subject_description, subject_category)
VALUES (:subject_code, :subject_name, :subject_grade, :subject_description, :subject_category);
SET #last_id = LAST_INSERT_ID();
INSERT INTO tutorsubject
(tutor_id , subject_id)
VALUES (:tutor_id, #last_id);");
//commit
$this->db->query("COMMIT;");
MySQL is trying to execute all these as one query and it doesn't recognise the whole command as separate queries. PhpMyadmin separates them on its own and that's why they run correctly there.
Something is adding apostrophes around database and table names. This is syntactically wrong (unless you have a certain ansi mode turned on). They need to be backtics (`).

fatal error in php and mysql

i am having a problem with my script in php/mysql. here is the error displayed by the server:
Fatal error: Uncaught exception 'PDOException' with 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 'if exists (select * from notificacoes where uid in () order by id desc' at line 1' in C:\wamp\www\bigui\classes\Notificacoes.class.php on line 57
and here is my php code:
static function listar(){
$strIdAmigos = Amizade::$strIdAmigos;
$query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc');
return $query->fetchAll(PDO::FETCH_ASSOC);
}
my table in the mysql is empty, with no values. when i insert a value in it, the error goes away and everything is fine. any help?
If $strIdAmigos is empty, it causes syntax errors.
Before you execute this query, you should check the $strIdAmigos value whether it's empty or not to avoid this issue. Not to forget to escape the values if needed.
When you run your query with nothing in the variable $strIdAmigos, it will error out.
Try initializing and/or checking your variable, $strIdAmigos, before running your query:
$strIdAmigos = "";
if (empty($strIdAmigos)) {
/* Uh oh, throw an error */
} else {
$query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc');
}
Note that if $strIdAmigos = "0" , the empty($strIdAmigos) will still evaluate to true and, hence, will NOT run the query.

Yii CDbCommand failed to execute the SQL statement: SQLSTATE[42000]:

I get this error when I didn't do anything for a while, I'm not sure if this is a Session problem or not.
The error message is:
CDbCommand failed to execute the SQL statement: 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 '=='1')' at line 1. The SQL statement executed was: SELECT * FROM games_developers_app t WHERE (status LIKE :ycp0) AND (developer_id==:ycp1)
The code is:
public function actionSortReject(){
$util = new Utility();
$util->detectMobileBrowser();
$util->checkWebSiteLanguageInCookies();
$this->layout = "masterLayout";
$count = '0';
$id = Yii::app()->user->getState('id');
$searchsort = "REJ";
$sort = new CDbCriteria();
$sort->addSearchCondition('status', $searchsort);
$sort->addCondition('developer_id='.$id);
$models = GamesDevelopersApp::model()->findAll($sort,array('developer_id'=>$id));
$this->render('/register/applist',array('models'=>$models,'count'=>$count));
}
It seems that everything worked fine, if I missed something in my code please tell me. Thanks =)
The problem is a combination how you have called compare and added additional parameters to findAll.
Your compare should be as follows:
$sort->compare('developer_id', $id);
And your findAll should be:
$models = GamesDevelopersApp::model()->findAll($sort);
You could also use addCondition as follows:
$sort->addCondition('developer_id=:developer_id');
$sort->params[':developer_id'] = $id;

Erreur : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;

when i try to execute an update statement i got the following error :
Erreur : 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 'Issy-les-Moulineaux ' where ssiphone_idstation=46' at line 1
my update statement is :
$bdd->exec("update ssiphone_stationdeservice set $cle='$element' where ssiphone_idstation=$id");
this is in a php code, THX in advance for your help :)
$cle and $element are in array, my code is :
foreach($table1 as $cle => $element)
{
$bdd->exec("update ssiphone_stationdeservice set $cle='$element' where ssiphone_idstation=$id");
}
now table1 is an array which contain the columns name of my table and its values :
$table1=array();
$table1['ssiphone_etatstation']=$etat;
$table1['ssiphone_commerce']=$commerce;
$table1['ssiphone_stationdelavage']=$lavage;
$table1['ssiphone_typescarburants']=$lescarburants;
$table1['ssiphone_joursdelasemaine']=$jourssemaines;
$table1['ssiphone_horaires ']=$this->horaires;
$table1['ssiphone_telephone ']=$telephone;
$table1['ssiphone_sensdecirculation ']=$this->sensDeCirculation;
$table1['ssiphone_adresse ']=$this->adresse;
$table1['ssiphone_ville']=$this->ville;
$table1['ssiphone_departement']=$this->departement;
$table1['ssiphone_nomstation ']=$this->nomStation;
Most likely your $cle variable isn't set, making the query look like:
... set ='Issy-les-moulineaux ' where ...
comment followup:
Change your code to look like this, then:
$query = "update ssiphone_stationdeservice set $cle='$element' where ssiphone_idstation=$id";
$result = $bdd->exec($query);
if ($result === FALSE) {
print_r($bdd->errorInfo());
die("Query: " . $query);
}
This way you have the complete query string in a variable you can inspect (e.g. by echoing out). Obviously there's something wrong with the query - but the mysql error string doesn't show the entire query, so you have to take measures to capture it.

Categories