update query throws error in mysql [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I have a table named 'mostread' with 2 columns open_id(int) and read(int). Now the problem is if 'open_id' is already present in the table then i need to update the 'read' for every click else i need to insert a new row with 'open_id' retrieved from the controller and read=1. I am using the below code in my model which inserts a new row properly but the second time i click it throws an error as follows.
A Database Error Occurred
Error Number: 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 'read = read+1 WHERE open_id = '193'' at line 1
UPDATE mostread SET read = read+1 WHERE open_id = '193'
Filename: D:/Xampp/htdocs/opunletter/opunletter/application/models/Select.php
Line Number: 52
public function click($id)
{
$query = $this->db->query("SELECT * FROM mostread WHERE open_id='$id'");
$count= $query->num_rows();
if($count > 0) {
$this->db->set('read', 'read+1', FALSE);
$this->db->where('open_id', $id);
$this->db->update('mostread');
$data = array(
'open_id' => $id,
'read' => '1'
);
$this->db->insert('mostread', $data);
return TRUE;
}else{
return FALSE;
}
}

Try adding backticks arround read its a reserved keyword in mysql
$this->db->set('`read`', '`read` + 1', FALSE);

Related

PDO param is reading as a string and not an int [duplicate]

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 5 years ago.
I want to pass a GET var into the query to set the OFFSET.
try {
$sql_offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
$main_query = "SELECT * FROM Orders
LIMIT 150 OFFSET :offset";
$result = $db->prepare($main_query);
$result->bindParam(':offset', $sql_offset, PDO::PARAM_INT);
$result->execute();
} catch (Exception $e) {
$error = $e->getMessage();
echo "<h2>".$error."</h2>";
die();
}
The query fails and the error message received is:
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 ''450'' at line 2
Note: If I place 450 directly into the query it works fine.
It seems to me that the problem is that it is reading the param as a string '450' and not an int 450. I tried solving that with the PDO::PARAM_INT - didn't help. I parsed the value with (int)$sql_offset and int_val($sql_offset) and didn't help. Meaning, I was still receiving the same error message.
Question: am I right? Is the problem that it is seeing as a string? If so, how can I fix?
Or is there a different problem here?
Try to parse value in int then check:
$sql_offset = (int)(isset($_GET['offset']) ? $_GET['offset'] : 0);

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);
}

Proper way to escape query in Codeigniter [duplicate]

This question already has answers here:
Update the value of a field in database by 1 using codeigniter
(3 answers)
Closed 24 days ago.
$sql = ("update Inventory SET ? = ?+1 WHERE ID= ?");
$query = $this->db->query($sql, array($field,$field,$id))->affected_rows();
The 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 ''Upvotes' = 'Upvotes'+1 WHERE ID= 386464' at line 1
Basically it's adding quotes around the Upvotes field causing it to be a malformed query what's the most practical way to remove the single quotes or rewrite the query entirely?
The answers here arn't quite right, as they are expecting you to already have the upvote count. I think this is what you're looking for:
$this->db->where('ID', $ID);
$this->db->set('Upvotes', 'Upvotes+1', FALSE);
$this->db->update('Inventory');
Use the line below to confirm the output it should give you something like:
echo $this->db->last_query();
UPDATE Inventory SET Upvotes = Upvotes+1 WHERE ID = 386464
The third paramater of false tells CI to not protect the query with backticks.
When possible, try to use CI's query builder to lower the chances of syntax errors. As per Codeigniter Documentation:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('Inventory', $data);
In your case, you are probably looking for something like this:
$data = array(
'Upvotes' => $upvotes + 1
);
$this->db->where('CARD_ID', '386464');
$this->db->update('Inventory', $data);
Now, if you want to run a custom code that you cant run using CI's query builder class, then do this:
$custom_sql = "update Inventory SET Upvotes = Upvotes + 1 WHERE CARD_ID = 86464";
$query = $this->db->query($custom_sql);

Can't Read static::$table_name after looping [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I get the following error messages:
Warning: PDOStatement::execute(): 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 '' at line 1 in /home/u522148874/public_html/includes/database-objects.php on line 27
Warning: PDOStatement::execute(): 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 '' at line 1 in /home/u522148874/public_html/includes/database-objects.php on line 27
Sample 1
Sample 2
When using the following code:
public function __construct(){
global $MySQLDatabase;
global $news;
$this->dbh = $MySQLDatabase->open_connection();
// Convert Table Fields in to Attributes
static::$db_fields = $this->get_dbFields(static::$table_name);
foreach(static::$db_fields as $field){
$this->$field = "";
}
}
// Get Table Fields from the Database
public function get_dbFields($table_name){
$sql = 'DESCRIBE ' . $table_name ;
$query = $this->dbh->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
// Get the quantity of the Table Columns
$count = count($result);
$field = array();
// Loop through each column to get the 'Field'
// ($count - 1) -> $count is minus 1 because array count starts with zero
// Example : Table Have 8 Columns
// $count will read it as 1 - 8 while array ($result[i]) reads it as 0 - 7
for($i = 0; $i <= ($count - 1); $i++){
$field[] = $result[$i]->Field;
}
return $field;
}
Can anyone explain to me why I am having those errors above but still can get the output (Sample 1 and Sample 2) above?
Here is my Complete Code: http://pastebin.com/xypkzs30
The problem is in the method DatabaseObjects::instantiate. The first line says
$object = new self;
Now, self is a reference to the current class, that means the class in which the instantiate-method is implemented (DatabaseObjects) and not the class on which it is called.
So you don't create new News objects where the table_name is defined but DatabaseObjects objects which have no table_name defined.
You can resolve this by creating new instances using the "late static binding"-version:
$object = new static;
That way the method creates new News objects. You might want to also mark the DatabaseObjects class as abstract, so no accidental instantiation occurs.
Plus you might want to globally cache the get_dbFields method - otherwise you hit the DB for every instantiation of the News class (your users might fall asleep using your app).

Two WHERE statements [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
I've done a search and couldn't find anything that could specifically help me.
I was hoping you could help.
I'd like to execute a MySQL query which searches a table for entries which meet two criteria (type = green AND on = yes)
I am presented with: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /link/to/my/file.php on line 36
Here is an extract from the code (line 36):
`$green = "SELECT * FROM homepage_vars WHERE type = 'green' AND on = 'yes'";
$green = mysql_query($green);
$green = mysql_fetch_array($green);`
ON is a MySQL reserved keyword. If you use it as a column or table identifier, you need to enclose it in backquotes:
SELECT * FROM homepage_vars WHERE type = 'green' AND `on` = 'yes'
You'll then have another problem once the query syntax is corrected. You have overwritten the variable $green several times. Originally, it held your query SQL, but was then used for the query result resource. That's fine, but then you will overwrite it with the row fetched by mysql_fetch_array() and its contents will be an array or FALSE. Subsequent attempts to fetch rows will fail since $green is no longer a result resource.
Always test for query success or failure before attempting to fetch rows. Call mysql_error() to see the error reported by the MySQL server, which would have pointed to invalid syntax near 'on or something similar.
$green = "SELECT * FROM homepage_vars WHERE type = 'green' AND on = 'yes'";
$query = mysql_query($green);
if ($query) {
// Don't overwrite your query resource!
// Use a new variable!
$row = mysql_fetch_array($query);
}
else {
// Failure!
echo mysql_error();
}

Categories