Proper way to escape query in Codeigniter [duplicate] - php

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

Related

Invalid parameter number: parameter was not defined in C:\wamp\www\stage\core\addUsers.php on line 20 [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
PDO: error handling
(2 answers)
Closed 3 years ago.
I get this error Invalid parameter number: parameter was not defined in C:\wamp\www\stage\core\addtUsers.php on line 20
if(!empty($_POST["add_record"])) {
require_once("connection.php");
$data = [
'username' =>$_POST["username"],
'password' =>$_POST["password"],
'role' =>$_POST["role"],
'photo' =>$_POST["photo"],
'nom-prenom' =>$_POST["nom-prenom"]
];
$sql = "INSERT INTO users(username,password,role,photo,nom-prenom) VALUES (:username,:password,:role,:photo,:nom-prenom)";
$statement = $pdo->prepare( $sql );
$result = $statement->execute($data);
if (!empty($result) ){
header('location:users.php');
}
}
You can't use - in the name of a placeholder. This will be understood as an arithmetic subtraction.
Consider this example:
$pdo->prepare('SELECT :num-1')->execute(['num'=>5]);
It looks for a param called :num or num and then it will subtract 1 from it.
A good IDE might even help you out by highlighting this:
Although with letters it would highlight it the same color as a column name, which could also be missed.
Try to use a different placeholder name e.g. :nom_prenom

Error with PHP parameters in SQL function call

I have two PHP variables in a class that are integers ($id and $descCode).
I'm trying to get these into my SQL function call as characters (the database is looking for these to be CHAR 2 and CHAR 10 respectively).
For some reason, this is triggering an error:
Use of parameter marker or NULL not valid
What exactly am I doing wrong here?
$results = array();
$results = $db->select("SELECT newCodeTest(:id,:desc) as newCode FROM testTable",
[
'id' => (string)$id,
'desc' => (string)$descCode
]
);
You can not use PDO in this way.
Look at this (possible duplicate): Can PHP PDO Statements accept the table or column name as parameter?.
Set those values as basic string
$id = $pdo->quote($id);
$desc = $pdo->quote($desc);
"SELECT newCodeTest({$id},{$desc}) as newCode FROM testTable"
Info about quoting:
https://www.php.net/manual/en/pdo.quote.php
Interesting info about performance
https://www.php.net/manual/en/pdo.quote.php#122967

update query throws error in mysql [duplicate]

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

using form variables for mysql query

I'm trying to fetch a result from a mysql table using two form variables namely $sessionID and $semesterID. I used the following code and it seems to have an error in the sql syntax
<?php
...
mysql_select_db($database_connChePortal, $connChePortal);
$query_rsRegcourses =sprintf("SELECT * FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s",$sessionID,$semesterID);
$rsRegcourses = mysql_query($query_rsRegcourses, $connChePortal) or die(mysql_error());
$row_rsRegcourses = mysql_fetch_assoc($rsRegcourses);
$totalRows_rsRegcourses = mysql_num_rows($rsRegcourses);
print_r($query_rsRegcourses); die;
...
?>
I tried running the query and I have the following error report
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 'AND vwr.semesterID=' at line 1
thanks
I think you should surround your variable with single quotes '' please change as follow
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'"
Put the %s in single quotes like this
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'",$sessionID,$semesterID);
To insert a variable into query, you have to properly format it.
Two other answers contains improper formatting - so, you shouldn't follow them.
To make formatting more handy, you have to encapsulate sprintf() into function like this:
function paraQuery()
{
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val)
{
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$result = mysql_query($query);
if (!$result)
{
throw new Exception(mysql_error()." [$query]");
}
return $result;
}
which would apply proper formatting and also will handle errors
Also note that your way of counting records is extremely inefficient and may cause server to hang. You have to query the only data you need. So, if you need only count - request the count only
so, the code would be
mysql_select_db($database_connChePortal, $connChePortal);
$sql = "SELECT count(*) FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s";
$res = paraQuery($sql,$sessionID,$semesterID);
$row = mysql_fetch_row($res);
print_r($row[0]); die;
it will make your query properly formatted and thus invulnerable to SQL injection
also, it seems that $semesterID is not set which may cause some problem too

CodeIgniter check if query succeeded [duplicate]

This question already has answers here:
How can I detect a create, update, delete query is successful in Codeigniter
(2 answers)
Closed 2 years ago.
I searched online and most of them suggest to use num_rows or similar functions to check if the query has been successful in CodeIgniter, however I am using an update function
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
// Produces:
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id
How would I check if this query was successful.
Use $this->db->affected_rows()
affected_rows() won’t give you proper results with this method, due to the very nature of how it works. Instead, update_batch() returns the number of rows affected.
ELSE TRY USING:
$result = $this->db->update('mytable', $data);
if ($result) {
return 1;
}

Categories