CodeIgniter UPDATE works on first, but not successive AJAX calls - php

This is the weirdest problem. My update query works consistently if I write it as a query string. Here's my model function:
public function approveListing($params)
{
//This always works.
$sql = "UPDATE `assets` set approved = ".$params['approved']." WHERE as_id = ".$params['as_id']."";
$this->db->query($sql);
// and I use this select query to detect the actual updated value change.
$this->db->select('approved');
$this->db->where('as_id', $params['as_id']);
$query = $this->db->get('assets');
foreach($query->result() as $row)
{
$params['approved'] = $row->approved;
}
return $params;
}
...and the output will look something like this:
as_id = 260
approved = 1 (or 0, if the input param is 0)
But if I use the query builder method, rather than a sql string, it works exactly once:
public function approveListing($params)
{
// This only works on the first ajax call. After that, no update occurs.
$this->db->set('approved', $params['approved']); // this will be a value of 1 or 0
$this->db->where('as_id', $params['as_id']);
$this->db->update('assets');
$params['updated'] = $this->db->affected_rows();
// and I use this select query to detect the actual updated value change.
$this->db->select('approved');
$this->db->where('as_id', $params['as_id']);
$query = $this->db->get('assets');
foreach($query->result() as $row)
{
$params['approved'] = $row->approved;
}
return $params;
}
...and the output will look something like this:
as_id = 260
approved = 1
updated = 0 <!- notice this is the affected_rows() value. :( ->
$params['approved'] is either a 1 or a 0. The field approved in table assets is a BIT(1)
The function is being called from a controller function, which itself is being called from an ajax call, which sends the changes of a set of radio button clicks (either '1' or '0').
In the case of the query builder update, I am also capturing the affected_rows. The first time I do the query, the affected_rows() = 1. Every time thereafter, the affected_rows = 0, and by checking the record in PHPMyAdmin, I can see the value just doesn't want to change.

Well, I really dislike answering my own questions, but since I did find an answer, and since the question (though rare) is not "too local", but is, in fact, something other coders are going to run into if they try to update a MySQL data type BIT (why we don't see a lot of questions about data type BIT is because it's one of the newest MySQL or MariaDB data types), here is what's going on.
CodeIgniter query builder wraps the value with single quotes, like so:
UPDATE `assets` set approved = '1' WHERE as_id = 260
MySQL doesn't like that. You could either just hand write your query, like this:
$sql = "UPDATE `assets` set approved = ".$params['approved']." WHERE as_id = ".$params['as_id']."";
$this->db->query($sql);
...But that's not a good solution, it's a copout. The query builder should work.
What you have to do is to declare the value as an INT, and the way you do it is like this:
$this->db->set('approved', (int) $params['approved']);
$this->db->where('as_id', $params['as_id']);
$this->db->update('assets');

Related

Subtract a number from a SQL Query in code-igniter framework

I am wondering how I can subtract 1 from a field in my database
i tried the following but it just set it to "-1", did not actually subtract it.
// update listing status to sold
this->db->update("listings", array("cases" => "cases" - 1,
Your code inserts -1 in the database because in PHP, "cases" - 1 evaluates to -1.
Try echo ("any_string"-1);. Read String conversion to numbers for details.
In CodeIgniter, you cannot use the the format of the function $this->db->update you have used directly to implement this query since the update function escapes all values passed to it.
However, you can use the following code to implement the same.
//Passing false as third parameter turns off escaping
$this->db->set('cases', 'cases - 1', false);
$this->db->where('id', $id); //Your where condition
$this->db->update('listings');
Alternatively, you can write the query manually and use the query function.
$sql = "UPDATE `listings` SET `cases` = `cases` - 1 WHERE [your where condition]";
$this->db->query($sql);
$this->db->set('cases','`cases`-1',FALSE);
$this->db->where('id', $id);/*whatever condition you want*/
$this->db->update('yourtablename');
Heres a link from codeigniter userguide:
https://codeigniter.com/user_guide/database/query_builder.html

SQL UPDATE value as null or string

I searched almost whole internet, but could not find something similar, yet my question looks so simple.
I have a php code like so:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = null;
}
... which simply checks if submitted value is empty or not, if it is empty, then variable $port1 = null;
then, further in the code, I need to insert this value/update it in the database
$sql_update = ("UPDATE names_10 SET `digName1`=$port1 WHERE `device_id`='$id'");
...which should set the "digname1" to null. but it won't!
I tried every combination, every type of quotes, but every time I got UPDATE error..
any ideas?
Try this:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = "NULL";
}
$sql_update = ("UPDATE names_10 SET `digName1`= $port1 WHERE `device_id`='$id'");
I would rather suggest you to use PDO when you plan to bind something like this. There are a lot of benefits using PDO that would amaze you!

Why is my php "if statement" not affecting my mysql query?

First of all, I know mysql is deprecated. Will change to mysqli as soon as I figure out the issue at hand. My query continues to update all my rows even if the data is not set in the 'stripetoken' column. Why is this happening?
Code snippet:
$token_query = 'SELECT * FROM jobsubmission';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_array($token_res);
if(isset($token_row['stripetoken'])) {
$updqry = 'UPDATE jobsubmission SET assigned=1 WHERE ID="'.$book_ids[$jcount].'"';
$update = mysql_query($updqry);
$bookdate = date("d-m-Y");
Because $token_row['stripetoken'] is always set because it is a column in your database and it will be available in $token_row as a result. Now whether it has a value or not is a different story. You should be using empty() instead (assuming you don't want it to be true for falsy values).
if(!empty($token_row['stripetoken'])) {
So while #JohnConde was absolutely correct in saying I needed to use the empty function over the isset, my solution layed elsewhere. Here is how I managed to get the query to work to my specifications:
instead of searching for empty, I made the 'stripetoken' column NULL
by default.
This allowed me to use the following code:
$token_query = 'SELECT * FROM jobsubmission WHERE ID="'.$book_ids
[$jcount].'" and stripetoken is not null';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_object($token_res);
if(!$token_row->stripetoken == NULL) {

mysql query yii not getting value

i have an issue gettin' the value from a query:
public static function sa() {
$resul = Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->execute();
$got = mysql_query($result);
$res = $got['MAX(id)'] + 1;
$rs='SA'.$res;
return "{$rs}";
}
it always return SA1, but i want get the last id and after plus 1 so in this case i have the next autoincremental id from my id column.
For example: i am creating a new registry with the field SA0000005. This number is calculated getting the last autoincremental value plus 1.
thanks for your valuable help
$resul = Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->execute();
$got = mysql_query($result); // what are you even doing here
Apart from typos, that's not how you are supposed to use the query builder. Have you read the documentation on the query builder?
The probable reason why you always get SA1, is because the $got['MAX(id)'] expression is NULL. You add 1 to that. You want something like this.
// returns false on no-result, MAX('id') otherwise
Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->queryScalar();

mysql query not running correctly from inside the application

I am completely stumped. Here is my php (CodeIgniter) code:
function mod()
{
$uid = $this->session->userdata('uid');
$pid = $this->input->post('pid');
if ($this->_verify($uid,$pid))
{
$name = $this->input->post('name');
$price = $this->input->post('price');
$curr = $this->input->post('curr');
$url = $this->input->post('url');
$query = $this->db->query("UPDATE items SET
name=".$this->db->escape($name).",
price=".$this->db->escape($price).",
currency=".$this->db->escape($curr),",
url=".$this->db->escape($url)."
WHERE pid=".$this->db->escape($pid)." LIMIT 1");
}
header('location: '.$this->session->userdata('current'));
}
The purpose of this code is to modify the properties (name, price, currency, url) of a row in the 'items' table (priary key is pid). However, for some reason, allowing this function to run once modifies the name, price, currency and url of ALL entries in the table, regardless of their pid and of the LIMIT 1 thing I tacked on the end of the query. It's as if the last line of the query is being completely ignored.
As if this wasn't strange enough, I replaced "$query = $this->db->query(" with an "echo" to see the SQL query being run, and it outputs a query much like I would expect:
UPDATE items
SET name = 'newname',
price = 'newprice',
currency = 'newcurrency',
url = 'newurl'
WHERE pid = '10'
LIMIT 1
Copy-pasting this into a MySQL window acts exactly as I want: it modifies the row with the selected pid.
What is going on here???
Now I feel stupid: all it took was seeing my code in a different font. My code has
currency=".$this->db->escape($curr),",
instead of
currency=".$this->db->escape($curr).",
The echoing made it work just fine because apparently you can give echo more than one string, comma separated, and it concatenates them
cries I spent hours on this
I know you answered your own question, but let me just add this to the pile: You're not leveraging CodeIgniter AT ALL in this sort of query - which if you used CI as it's intended, you wouldn't have had that typo. Your query should look like this (among other things):
$query = $this->db->update('items',
array('name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'curr' => $this->input->post('curr')),
array('id' => $this->input->post('id')),
1);
By assembling the query string by hand, you're undoing what CI does for you. Only when you're using some complex JOIN statement should you be writing your own SQL in CI, and even then, you want to use the sprintf PHP function to make sure you're not introducing typos.

Categories