update json data in sqlite3 - php

I have this table:
id
data
1
{"customers":[{"name": "test1","number": 1111},{"name": "test2","number": 2222}],"enableCheck": true}
And my new values:
$new_customer_name = "test3";
$new_customer_number = "3333";
I need a query to add this new values to the data column, I want this:
id
data
1
{"custumers":[{"name": "test1","number": 1111},{"name": "test2","number": 2222},{"name": "test3","number": 3333}],"enableCheck": true}
I try to use select query and edit json and update data but i need a query to update JSON directly into JSON of data

I found this and work:
UPDATE inbunds SET data = JSON_INSERT(data, '$.customers[2]', json('{"name": $new_customer_name,"number": $new_customer_number}')) WHERE id = 1
But now i need count JSON/s in $.customers and add JSON/s into end of $.customers

Related

How Make Links For Array Data In MySQL And PHP

i want make a different link for array data in mysql database.
for example i store data like below in my database:
data1,data2,data3 in one column
and i want fetch them like below by one query:
echo'
data1
data2
data3';
If your data is stored as "data1,data2,data3" in a column named "column" of your table:
$data = explode(",", $row["column"]);
echo 'data1';
But as said above, you should avoid storing multiple data in one column.
Something like this in your database retrieving loop :
$data = explode(',',$row['COLOUMN_NAME']);
echo'
data1
data2
data3';

PHP wpdb get_var query returning zero

I have the following code, which is adding some data to a database via server side API. The field order_number should be created via $OrderNumberNext, which is calculated by a count(*)+1 as order_num variable.
However, checking the database after this is done shows that this only ever calculates as 0 (zero). Should I be using a different function call for this?
function addChartToSet($chartId, $setId){
$chartWithId = $this->db->get_var($this->db->prepare("select id from chords where chord_id=%s",$chartId));
$setWithId = $this->db->get_var($this->db->prepare("select id from sets where set_id=%s",$setId));
$orderNumberNext = $this->db->get_var($this->db->prepare("select count(*)+1 as `order_num` from `chords_inside_sets` where `set_id`=%s",$setId));
$this->db->query($this->db->prepare("update sets set `last_updated_time`=NOW() where `set_id`=%s",$setId));
$this->db->query($this->db->prepare("insert into `chords_inside_sets` set `chord_id`=%s , `set_id`=%s, `order_number`= %s",$chartWithId,$setWithId,$orderNumberNext));
return array("last_updated_time"=> $this->getMaxUpdatedTimeForSet($setId), "query"=> $this->db->last_query);
}
You are adding 1 inside the query that fetches the data. It cannot work. Get your count first through the SELECT query, then add one on the next line, like this:
$orderNumberNext = $this->db->get_var($this->db->prepare("select count(*) as `order_num` from `chords_inside_sets` where `set_id`=%s",$setId));
$orderNumberNext++;

Updating table using string mysql

I have this string response coming from the server :
string '{"code":1,"status":200,"data":
[{"connect_id":"3","equipment_id":"1","sample_id":"33","test_id":"44","message_type":"test_ordered","sent_date":"0000-00-00"},
{"connect_id":"12","equipment_id":"34","sample_id":"234","test_id":"234","message_type":"asdasd","sent_date":null}]}'
I have to update my local table's fields using the values found in "data".
In case a value coming from the response is NULL (on a particular field from "data"), there should be no changes to that field when updating the local table.
The table to be updated has many fields but let's say I want to update only the following three fields: equipment_id,sample_id,test_id.
After the update is succesfull I have to send back a response to the server telling that the transaction was succesfull and to update it's status (which is a field of the table's server from where the data has been collected to send the response) so the server won't send the response twice.
I'm assuming you're using PDO and a valid pdo-connection in variable $dbc. I assume further that you identify your rows via the connect_id. You should change this according your needs.
Following code should give you an outline how to tackle this. Please regard my comments. I doesn't have done all for you, especially omitted the error handling.
$result = json_decode($response, true);
// You should validate that the decoding was successful and
// that the result contains all the data you expect.
// You find your data as in $result['data']
// This is an (numbered) array of associative arrays with your "columns" as key
// and the data as value
// prepare your update statement
$q = $dbc->prepare('
UPDATE mytable
SET
equipment_id = ?,
sample_id = ?,
test_id = ?
WHERE
connect_id = ?
');
foreach ($result['data'] as $row) {
// and execute it while looping through the data-array with
// the appropriate data. Please note that the order of the
// parameters got to be the same as in the prepared statement
$params = array(
$row['equipment_id'],
$row['sample_id'],
$row['test_id'],
$row['connect_id']
);
$q->execute($params);
// check success of the execute too.
}

Mysql to Json. Can this be solved using MySQL?

I have a MySQL query that will be converted to JSON and used in Obj C for each user with a specific id. I believe that this is a MySQL puzzle, but there may be an answer in JSON. I don't ask many questions, so I'll try to make it concise.
Here is a screen shot of values for one user. If you notice, the field_id may vary because not all info is required, so the id field will vary from 3 to 8 values for a given user_id:
I have to make a query where the results GROUP BY column1 (user_id), but only WHERE column2 (field_id) has the following values field_id='18' and field='19', Then (THE BIG PROBLEM) I need to populate the results in one GROUP with both values of column3 (value) so I can get results in one JSON object.
I already know how to convert to JSON for use in iOS, but I can only get it to give me results as two objects.
My current query
$query = "SELECT * FROM table1 WHERE field_id='18' OR field_id='19' ORDER BY user_id ";
Current Result
[{"id":"5","user_id":"461","field_id":"18","value":"1_MX4zNjcxNzM5Mn4x...","access":"0"},
{"id":"6","user_id":"461","field_id":"19","value":"T1==cGFydG5lcl9pZD0...","access":"0"},
{"id":"11","user_id":"463","field_id":"18","value":"1_MX4zNjcxNzM...","access":"0"},
{"id":"12","user_id":"463","field_id":"19","value":"T1==cGFydG5lcl9...","access":"0"}]
I need the two JSON objects with matching user_id fields as one object with results that differentiate field='18' value from field='19' value. Something like:
[{"id":"5","user_id":"461","field_id":"18","value18":"1_MX4zNjcxNzM5Mn4x...","value19":"T1==cGFydG5lcl9pZD0...","access":"0"},
{"id":"11","user_id":"463","field_id":"18","value18":"1_MX4zNjcxNzM...","value19":"T1==cGFydG5lcl9...","access":"0"}]
OR
[{"id":"5","user_id":"461","field_id='18'":"1_MX4zNjcxNzM5Mn4x...","field='19'":"T1==cGFydG5lcl9pZD0...","access":"0"},
{"id":"11","user_id":"463","field_id='18'":"1_MX4zNjcxNzM...","field='19'":"T1==cGFydG5lcl9...","access":"0"}]
THANKS...
I'm not 100% sure if this will work. I cannot easily try the JSON output of it. But what if you run a query like this?
SELECT id, user_id,
GROUP_CONCAT(field_id,':',value) field_id,
access
FROM table1 WHERE field_id='18' OR field_id='19'
GROUP BY user_id
ORDER BY user_id
You probably want to to look at handling this in PHP when reading in the result set.
So use your current query of
SELECT * FROM table1 WHERE field_id='18' OR field_id='19' ORDER BY user_id
But build result data object like this:
$results = array();
$i = -1;
$current_user_id = '';
while ($row = [YOUR MySQL FETCH MECHANISM HERE]) {
// determine if this record represents a new user id in the result set
// if so, we need to set up the user object and start another entry in top level array
if($current_user_id != $row['user_id']) {
// you have moved to a new user in the result set
// increment your array counter and set current user id
$i++; // will set value to 0 on first iteration
$current_user_id = $row['user_id'];
// build new array entry
$results[$i] = new stdClass();
$results[$i]->user_id = $current_user_id;
$results[$i]->fields = array();
}
// build field object for insertion
$field = new stdClass();
$field->field_id = $row['field_id'];
$field->value = $row['value'];
$results[$i]->fields[] = $field;
}
On encoding $results this would give you a JSON structure like this:
[
{
"user_id":"461",
"fields": [
{
"field_id":"18",
"value":"foobar"
},
{
"field_id":"19",
"value":"abcxyz"
}
]
},
...
]
This data structure is going to be more readily usable by consuming app than some solution which requires exploding concatenated field id/value strings. Also note that I have not included id field anywhere in data structure, as it has no meaning in this context. If you truly needed that id, you could add it as another property in the field object since that is where there is a one-to-one relationship (not with user_id).
Based on your comment, if the field value is known and you need to access it via field_id index, you can slightly modify what I have shown above to build index-able field listing rather than a simply array of objects:
$results = array();
$i = -1;
$current_user_id = '';
while ($row = [YOUR MySQL FETCH MECHANISM HERE]) {
// determine if this record represents a new user id in the result set
// if so, we need to set up the user object and start another entry in top level array
if($current_user_id != $row['user_id']) {
// you have moved to a new user in the result set
// increment your array counter and set current user id
$i++; // will set value to 0 on first iteration
$current_user_id = $row['user_id'];
// build new array entry
$results[$i] = new stdClass();
$results[$i]->user_id = $current_user_id;
$results[$i]->fields = array();
}
// insert field value at field_id index position
$results[$i]->fields[$row['field_id']] = $row['value'];
}
This would give you a JSON representation like this.
[
{
"user_id":"461",
"fields": {
"18":"foobar",
"19":"abcxyz"
}
},
...
]
This would allow easy look-up by client based on field id. Of course you may want to consider similar for user_id. From the user object you could just access fields->18 (or similar based on on client language syntax).

How to add to an array in a database and get back each array and display it

How can I add a value into an array in a database row, and then later on, when I want to get values of the array, simply display each different array value on a new line?
Also, how do arrays work in mysql and how to get the value of it?
Filed testField has serialized data.
$arrayData = array('one','two','three');
$serializedData = serialize($arrayData);
Mysql insertion:
insert INTO table ('testField') Values ($serializedData);
To get data:
select testField from table where id=1
You are getting here some string value. Then you should unserialize this string to get array:
$arrayData = unserialize($selectResultValue);
Look here for more details about serialize function:
http://php.net/manual/en/function.unserialize.php
MySQL does not have a native array data type. So, your first step is to figure out how you will store the elements of the array in a MySQL table.
Will you store each array element in its own database row?
elem val
1 value1
2 value2
...
n valuen
Or will you store the arraw as a series of concatenated values in a single row, something like this?
values
value1,value2,value3,...,valuen
In the first case, you can update a single array element easily:
UPDATE array SET val=newValue
WHERE elem=updatedElement
In the second case, you'll have to read the values column, break it out (deserialize it) into an array, change the element or elements you want to change, then gather it up (serialize it) back into a values column, and update your mySQL table. #Anthony pointed this out.
You need to answer the question about how you're storing the array before you can start to figure out how you will update it.
save array
$foo = array(1,2,3);
mysql_query(sprintf("INSERT INTO some_table ('foo') VALUES ('%s')", serialize($foo));
foo will appear as a string 1,2,3 in the database now
fetch array
$result = mysql_query("SELECT id, foo FROM some_table")
$item = mysql_fetch_object($result);
$foo = $item->foo;
$foo = unserialize($foo);
add data to array
$foo[] = 4;
$foo = array_uniq($foo); // you might want to ensure only unique values
mysql_query(sprintf("UPDATE some_table SET foo='%s' WHERE id=%d", serialize($foo), $item->id);
foo will appear as a string 1,2,3,4 in the database now

Categories