Update Object value from Array of Objects Codeigniter - php

I have a query result in values $some = $query->result() , now $some[0] should be about containing following properties:
name
type(A/B)
status(0/1)
Now status of all objects contain null so i want to set 0 if type is A , and 1 if type is B, hence come to simple looping of Array of Objects as well as modifying them while looping , How to do this?
Edit:
Code and table details are given below
Table `test`:
Name| Type| status
Ali | A | NULL
Zeeshan| A | NULL
Waqar| B | NULL
$query = $this->db->query("SELECT test.name as name,test.type as type , test.status as status FROM test");
$some = $query->result();

You should be able to use an UPDATE statement. Since you didn't specify which version of SQL you are using, I can list some links to documentation for UPDATE for several common database versions:
MySQL
PostGreSQL
SQL SERVER (Transact-SQL)
And you should be able to set the value for status conditionally using a CASE statement:
UPDATE test
SET status = CASE type WHEN 'A' THEN 0 ELSE 1 END
You can see this in action on this sqlfiddle.

Related

Return BLOB column Which is Empty Or Not Empty as 1 or 0

I have a table with BLOB column that some row has BLOB, some empty.
1 Apple BLOB-8KiB
2 Banana
3 Pear BLOB-6KiB
4 Orange BLOB-7KiB
Is there any way I can use PHP MYSQL to get the array like this:
$fruit = array(
array("1",Apple,1),
array("2",Banana,0),
array("3",Pear,1),
array("4",Orange,1)
);
I just want to change the BLOB data with 1, Empty with 0 in my PHP array. Pls help.
Your select statement can use IF and ISNULL (note these are not widely implemented in the same format on different database backends, this is for MySQL).
So you would use:
SELECT ID, Name, IF(ISNULL(BlobField), 0, 1) FROM TableName
IF allows you to choose one of two values according to a logical operation.
ISNULL returns true or false according to whether or not the value is NULL

MYSQL Select IN query using text

Any quick assistance will be highly appreciated. I've table row in mysql named as mob_categories, now data is being is saved as '|' separated for instance (cat 1|cat 2|cat 3 and so on. Now i need to get the value from another column in the same table if the input value matches.
for instance if the value is cat 1 i need to select the value from another column is named as deveice_token wherever it matches with 'cat 1'
I tried this code but its not working somehow
SELECT * from table_name where find_in_set('cat 1',mob_categories) <> 0
so i modified a bit with the following code but it works with only numeric value if the value exits in this format in this format (i.e) 1,2,3
$userNotification = $wpdb->get_results("SELECT * from table_name where 1 IN (mob_categories); ");
What's i'm missing specifically?
Since data in mob_categories are separated by | rather than by comma (,) so you need to make it compatible for FIND_IN_SET first.
So replace all the | by comma (,) first.
SELECT * from table_name where find_in_set('cat 1', REPLACE(mob_categories,'|',',')) > 0

mysql_query inject - replace returned field

im trying to learn and understand mysql inject, i have created demo case.
SELECT ret_variable FROM data WHERE name = '".$name."' AND age = ".$age;
then if(ret_variable == 2){something} but query originally returns 1 and i need to force it to output 2
How to modify $age variable to set custom output field for ret_variable(only in response) ?
I have tried few ways with OR but didn't wroked.
I see no practical application other than learning. I assume since you know the code , you have permission to test this out. So let's give it a go!
You can only return a 2 for the ret_variable when there is a row in the database with a value of 2 as the ret_variable and you know the name value of that row. You can for instance enter that name and the following to bypass the correct value for the age.
age AND ret_value = 2
That would create the following query:
SELECT ret_variable FROM data WHERE name = 'John' AND age = age AND ret_value = 2;
The principle of mysql injection is this sort of manipulation of the query. But you can not force a value which is returned unless there is a row in the database with this value for ret_variable and you can somehow select this row.
When you don't know the name (or there is no record of your known name with a ret_variable of 2) it is not possible.
Since the AND operator has precedence over the OR operator you cannot manipulate the query to give a 2 as ret_variable. This is because the name = '?' part will always fail.

Best way to decide between INSERT/UPDATE when unique ID is not available

Normally, when you are updating/inserting you use the on duplicate key update statement. But I'm inserting/updating such table:
id | neutral text | language | translation
---+--------------+----------+------------
0 | SUBMIT | en | Submit
1 | SUBMIT | cs | Odeslat
2 | SUBMIT | fr | Démarrer
I know I should've made 3 tables, but the project is not that large, so I decided to make it rather simple.
So now, when I want to change or add translation, do something like this:
/*
$this->lang_class->table = the name of my table
$offset = neutral text name
$this->lang = language name
$value = new translation
*/
$this->debug("Translate attempt!<br />");
//Try to update, insert will be performed if update returns 0 rows
$update = $this->pdo->prepare("UPDATE `{$this->lang_class->table}` SET content='$value' WHERE lang='{$this->lang}' AND name='$offset'");
$update->execute(); //try to update
if($update->rowCount()==0) { //If no update happened, insert
$this->debug("Creating new translation entry.<br />");
$this->execsql("INSERT INTO `{$this->lang_class->table}` (lang, name, content) VALUES ('{$this->lang}', '$offset', '$value')");
}
return $value;
The problem is, that sometimes it may happen, that the new translation matches the old. In such case, the UPDATE will return 0 rows and INSERT is performed.
So what approach should I use, if I want to stick to only one table?
The correct option is to create a unique composite index (name, lang) on your table and upsert the new value with ON DUPLICATE KEY UPDATE. This is exactly the very case why the ON DUPLICATE KEY UPDATE even exists in MySQL.
As you anyway running 2 queries, you can change first one:
SELECT count(*) FROM translate_table WHERE lang='$lang' AND name='$name';
And, after that, If this query returns 0, you can use your insert:
$this->execsql("INSERT INTO `{$this->lang_class->table}` (lang, name, content) VALUES ('{$this->lang}', '$offset', '$value')");
else run your update query:
$this->pdo->prepare("UPDATE `{$this->lang_class->table}` SET content='$value' WHERE lang='{$this->lang}' AND name='$offset'")->execute();
You can use key set on neutral_text and language fields. Especially that you should anyway create that key and it should be unique.

PHP MySQL max() function producing 5

I am working on a survey created by PHP and MySQL. So the issue is, I am trying to create a ResponseID, which is an ID specific for every person submitting the survey. So the code was created to add 1 to the existing max value from the ResponseID column. Here's the code:
//Response ID creation
$query = "SELECT max(ResponseID) FROM survey";
$res = mysql_query($query);
$RID = $res+1;
I know I can condense it, but here's the problem: I already entered one item on the table with the ResponseID of 1. When I tested the survey with different answers, the next ResponseID was 5. It should have been 2. So I tested again to see if it would produce 6 next time.
Unfortunately, it produced 5 again. I had my PHP guru looked it over and he said the coding was correct and it should be something from the database. I didn't set anything in the ResponseID except for it being an int. So why is it producing a 5? If anyone could please tell me how to go about fixing it, that would be super cool of you.
I am somewhat new to PHP.
$res will be a mysql statement handle, NOT the result of the query. you still have to actually FETCH a row from this $res result to access the value of the max() function in the query.
This handle probably internally has identifier #5, which is why you're getting that "odd" result.
The code should be:
$sql = "SELECT MAX(responseID) AS max ...";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$RID = $row['max'] + 1;
$res is a resource, not the value of the query, please read the manual: http://nz.php.net/manual/en/function.mysql-query.php
Why don't you use an AUTO_INCREMENT column and retrieve the new value using mysql_insert_id?
You need to use an AUTO_INCREMENT column for this. The problem is that if two instances of the PHP script are running at the same time (extremely likely assuming you're using a multithreaded server like Apache), then you could have a case like this:
|PHP #1 | PHP #2 |
=================================
|Accept client |(waiting) |
|SELECT MAX... |(waiting) |
|Send to MySQL | Accept client |
|(waiting) | SELECT MAX... |
|(waiting) | Send to MySQL |
|Get response 4 |Get response 4 | //Nothing inserted yet, max is still 4
|Try to insert 5| (waiting) |
|Succeeded | (waiting) |
|(waiting) |Try to insert 5|
| ... | Failed! |
(This in addition to what Dagon said)
Use $row = mysql_fetch_assoc($res) to get the resulting row from your query.
See mysql_fetch_assoc().
The reason why you are not getting the correct value is because mysql_query doesn't return a value, it returns a resource.
Try this instead:
//Response ID creation
$query = "SELECT max(ResponseID) FROM survey";
$res = mysql_query($query);
if($res !== FALSE) $res = mysql_fetch_array($res); // If $res === FALSE, something went wrong
$RID = $res[0] + 1;
Also I suggest you to use AUTO_INCREMENT on the ResponseID field, this makes your life a lot easier :)
i'm not really sure if i understood ur problem but if u wanna generate a response ID specific to every user or every survey posted, then what u can do is use auto_increment for the response ID. the response id will be incremented every time a new survey is posted. also get the last id posted using mysql_insert_id to get the last id posted.
so u can get the last id using
$last_id = mysql_insert_id ();
u need to put that statement right after ur query. that way u can get the last id.

Categories