I have a mysql database that looks like this
+----+----------+---------+----------------------------------+---------------------+
| id | field_id | user_id | value | last_updated |
+----+----------+---------+----------------------------------+---------------------+
| 1 | 1 | 1 | admin | yyyy-mm-dd hh:mm:ss |
| 3 | 5 | 1 | a:1:{i:0;s:2:"18";} | yyyy-mm-dd hh:mm:ss |
| 4 | 1 | 2 | testuser1 | yyyy-mm-dd hh:mm:ss |
| 5 | 5 | 2 | a:2:{i:0;s:2:"19";i:1;s:2:"18";} | yyyy-mm-dd hh:mm:ss |
+----+----------+---------+----------------------------------+---------------------+
I understand that a normal sql query will not be suitable so instead I need to pull all the data into php to then sort through it.
What I want is to get any user_id that has a number, lets say "19" in field_id 5. In that example, the array should read "2". Or I could search for "18" in field_id 5 and the array would return "1,2".
To get the database, I am using the following
<?php
global $wpdb;
$table_name = $wpdb->prefix . "bp_xprofile_data";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name" );
$strDB = maybe_unserialize( $retrieve_data);
echo print_r($strDB, true);
?>
Which returns:
Array ( [0] => stdClass Object ( [id] => 1 [field_id] => 1 [user_id] => 1 [value] => admin [last_updated] => 2017-09-21 12:38:20 ) [1] => stdClass Object ( [id] => 3 [field_id] => 5 [user_id] => 1 [value] => a:1:{i:0;s:2:"18";} [last_updated] => 2017-09-21 12:38:20 ) [2] => stdClass Object ( [id] => 4 [field_id] => 1 [user_id] => 2 [value] => testuser1 [last_updated] => 2017-09-23 01:43:50 ) [3] => stdClass Object ( [id] => 5 [field_id] => 5 [user_id] => 2 [value] => a:2:{i:0;s:2:"19";i:1;s:2:"18";} [last_updated] => 2017-09-23 01:43:50 ) )
I can't work out how I can then sort through this data. I tried to find sections of string but this was not working.
You should be able to use the LIKE comparison on the 'value' field, e.g.
SELECT * FROM $table_name AND value LIKE '%9%'
The difficulty with searching for a number is that LIKE will also return partial matches, so a query for 9 would also return 19, 91, 192 etc.
However, based on the values getting surrounded by double quoted in the serialised string, you should be able to search for the exact value by including the double quotes in the search string, e.g. "9".
Adding that into the code in your question, we get:
global $wpdb;
$num_to_find = 19; /* or change to whatever number you need */
$field_id_to_check = 5; /* or change to whatever number you need */
$table_name = $wpdb->prefix . "bp_xprofile_data";
$user_ids = $wpdb->get_results(
$wpdb->prepare(
"SELECT user_id FROM $table_name
WHERE field_id = %d AND value LIKE '%%\"%d\"%%'",
$field_id_to_check, /*this param replaces the 1st %d in the query */
$num_to_find /*this param replaces the 2nd %d in the query */
)
);
print_r($user_ids);
Note: because the query includes a variable and I don't know where its coming from, I've used $wpdb->prepare to sanitise the variable.
That's not tested, but I believe it should work!
Well, first rule – you should not do this. But if there is good reason, consider using such query for searching in index-based arrays
SELECT * FROM $table_name WHERE value REGEXP '.*;s:[0-9]+:"19".*'
Here we search on the column value the value "19" as you did on the example with a regex.
Regards.
Related
I have a table , similar to this:
| key | value |
|----------|-------|
| limit | 15 |
| viplimit | 25 |
| .. | |
And i have an array :
Array
(
[0] => Array
(
[key] => limit
[value] => 10
)
[1] => Array
(
[key] => viplimit
[value] => 99
)
...
Now , saying we have 100 rows. What would be the best way to update the table corresponding to the array ?
There would be the option of a query for each 100 row, but that is just bad performance.
This should work:
$statement = "UPDATE mytable
SET key = CASE id
WHEN 1 THEN 'key'
WHEN 2 THEN 'another_key'
WHEN 3 THEN 'some_key'
END,
value = CASE id
WHEN 1 THEN 15
WHEN 2 THEN 25
WHEN 3 THEN 45
END
WHERE id IN (1, 2, 3)
");
DB::statement($statement);
Just think how to create correct query. If it's admin panel or something that will be run not very often, I'd just use iteration to keep things simple.
given a very simple table structure thus:
mysql> describe songpart;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | MUL | NULL | auto_increment |
| partName | text | NO | | NULL | |
+----------+---------+------+-----+---------+----------------+
which results in an array like this in php (when queried)
Array ( [0] => Array ( [id] => 1 [0] => 1 [partName] => Lead Guitar [1] => Lead Guitar )
[1] => Array ( [id] => 2 [0] => 2 [partName] => Bass Guitar [1] => Bass Guitar )
[2] => Array ( [id] => 3 [0] => 3 [partName] => Drums [1] => Drums )
[3] => Array ( [id] => 4 [0] => 4 [partName] => Keyboard [1] => Keyboard ) )
Am I missing some simple trick to turn this into a simple array with id as the key like so:
Array ( [1] => Lead Guitar
[2] => Bass Guitar
[3] => Drums
[4] => Keyboard )
or is it possible to get PDO to deliver an array like this?
TiA
You can simply use the PDO::FETCH_KEY_PAIR is you have only 2 columns in your result.
You can also use the PDO::FETCH_GROUP and PDO::FETCH_ASSOC together if you have more. Example :
$result = $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
This will yield an array indexed with the first column containing at each index an array of the result for this key. You can fix this by using array_map('reset', $result) to get your goal.
Example :
$result = array_map('reset', $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
Try this:
$records = $pdo->query('SELECT id, partName FROM myTable');
$records->setFetchMode(PDO::FETCH_KEY_PAIR);
print_r($records->fetchAll());
For that you need to set only your desired fields in iteration.
$part_name = [];
$records = $pdo->query('SELECT * FROM your_table');
foreach ($records as $row) {
$part_name[$row['id']] = $row['partName'];
}
Questions
How should I do the query(ies) to get this results?
Should I use a different structure for database tables?
Details
I want to get results from 3 tables:
+------------------------------+-------------------+
| courses | id | <-------+
| | name | |
| | | |
+------------------------------+-------------------+ |
| sections | id | <-------|----------+
| | course_id | <- FK(courses.id) |
| | name | |
+------------------------------+-------------------| |
| resources | id | |
| | section_id | <- FK(sections.id)-+
| | name |
+------------------------------+-------------------+
I want to store results in a PHP Array like this:
Array
(
[courses] => Array
(
[id] => 1
[name] => course 1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => course 1 section 1
[resources] => Array
(
[0] => Array
(
[id] => 1
[section_id] => 1
[name] => resource 1
)
)
)
)
)
)
EDIT
What I did:
$cources = DB::query(Database::SELECT,
'select * from courses')->execute($db,false)[0]; // Get all courses as array
foreach($courses as &$course) {
$sections = DB::query(Database::SELECT,
'select * from sections where course_id = '.$courses['id']);
$course['sections'] = $sections;
foreach($course['sections'] as &§ion) {
$resources = DB::query(...); // Get array of resources
$section['resources'] = $resources;
}
}
The database structure is normalized - this is correct and should not be changed.
However, SQL returns de-normalized or "flattened" data for an N+ join: only a set of homogenous records can be returned in a single result-set. (Some databases, like SQL Server, allow returning structure by supporting XML generation.)
To get the desired array structure in PHP will require:
Separate queries/result-sets (as shown in the post): ick!
There will about one query/object. While the theoretical bounds might be similar, the practical implementation will be much less efficient and the overhead will be much more than for single query. Remember that every query incurs (at the very least) a round-trip penalty - as such, this is not scalable although it will likely work just fine for smaller sets of data or for "time insensitive" operations.
Re-normalize the resulting structure:
This is very trivial to do with support of a "Group By" operation, as found in C#/LINQ. I am not sure how this would be approached [easily] in PHP1. This isn't perfect either, but assuming that hashing is used for the grouping, this should be able to scale fairly well - it will definitely be better than #1.
Instead of the above, consider writing the query in such a way that the "flat" result can be used within the current problem/scope, if possible. That is, analyze how the array is to be used - then write the queries around that problem. This is often a better approach that can scale very well.
1 Related to re-normalizing the data, YMMV:
SQL result to PHP multidimensional array
PHP array to multidimensional array
Group a multidimensional array by a particular value?
You can try something like this
SELECT * FROM (
select c.id, c.name from courses c
union
select s.id, r.name,s.course_ID from sections s
union
select r.id, r.name,r.section_ID from resources r
)
You cant get multi dimensional result from mysql. The query for getting the elements should be like this:
select courses.id as coursesId,courses.name as coursesName,sections.id as sectionsId,sections.name as sectionsName,resources.id as resourcesId, resources.name as resourcesName
from courses
left join sections on courses.id=sections.course_id
left join resources on sections.id=resources.section_id;
But ofcourse it will not give you the array as you like.
if you are familiar with php then you can use this code i am writing only 2nd level you can write same way with third label
$final=array();
$c=-1;
$cid=false;
$cname=false;
$query = "SELECT c.*,s.*,r.* FROM courses AS c LEFT JOIN sections AS s ON c.id=s.course_id LEFT JOIN resources AS r ON r.section_id =s.id";
$result=mysql_query($query, $this->con) or die(mysql_error());
while($row= mysql_fetch_array($result)){
if($cid!=$row[2]){
$final['cources'][++$c]['id']=$cid=$row[0];
$final['cources'][$c]['name']=$cname=$row[1];
$s=-1;
}
$final['cources'][$c]['sections'][++$s]['id']=$row[2];
$final['cources'][$c]['sections'][$s]['course_id']=$row[3];
$final['cources'][$c]['sections'][$s]['name']=$row[4];
}
echo "<pre>";
print_r($final);
echo "</pre>";
//Outpur
Array
(
[cources] => Array
(
[0] => Array
(
[id] => 1
[name] => c1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => s1-1
)
[1] => Array
(
[id] => 1
[course_id] => 1
[name] => s1-1
)
)
)
[1] => Array
(
[id] => 2
[name] => c2
[sections] => Array
(
[0] => Array
(
[id] => 2
[course_id] => 2
[name] => s1-2
)
)
)
)
)
Lets say i have an array in my mysql row:
a:3:{i:1;a:3:{i:0;s:1:"1";i:1;s:1:"3";i:2;s:1:"5";}i:4;a:3:{i:0;s:2:"21";i:1;s:2:"25";i:2;s:2:"29";}i:5;a:1:{i:0;s:2:"33";}}
It looks like this:
Array
(
[1] => Array
(
[0] => 1
[1] => 3
[2] => 5
)
[4] => Array
(
[0] => 21
[1] => 25
[2] => 29
)
[5] => Array
(
[0] => 33
)
)
Now, i am passing an array through _GET and i want to print out all rows that contain same values both in my mysql and passed array. For example, if i pass this array:
Array
(
[1] => Array
(
[0] => 5
)
)
A result should be shown, because my passed array contains option 5. I tried to do it like this:
$pecul = serialize($array);
$q=mysql_query("SELECT id from table WHERE options like '%$pecul%'")or die(mysql_error());
but it only prints out results with identical arrays.
You probably want to unserialize the data that's in your database first. Once it's in a PHP array you can perform a check for those options, so say:
if(in_array("5",$array)) {
$q=mysql_query("SELECT id from table WHERE options=5")or die(mysql_error());
}
If you need to do a query for all of the options, you can do a loop like so:
foreach($array as $option) {
$q=mysql_query("SELECT id from table WHERE options='$option'")or die(mysql_error());
}
But like mario said, you may want to think the options mechanism over and perhaps serialized data isn't what you need. This should hopefully work for you the way it is though.
the like operator match only match same it does not understand for example you have dem in like than it will also show the demolish so
i think for that you need first unserlize and than find by php by either loop or in_array() function
what %like% do suppose this is table Persons and you used the query
SELECT * FROM Persons WHERE City LIKE '%tav%'
+-------------+-------------+
| id | city |
+-------------+-------------+
| 1 | Sandnes |
+-------------+-------------+
| 2 | Stavanger |
+-------------+-------------+
so the result will be
+-------------+-------------+
| id | city |
+-------------+-------------+
| 2 | Stavanger | <----it has tav (s-tav-anger)
+-------------+-------------+
IN() Check whether a value is within a set of values
mysql> SELECT 2 IN (0,3,5,7);
-> 0
mysql> SELECT 'wefwf' IN ('wee','wefwf','weg');
-> 1
SELECT val1 FROM tbl1 WHERE val1 IN (1,2,'a');
View: IN MySql
I Have a query
SELECT classid, COUNT(*) as cnt FROM tbl_name GROUP BY classid
on Table
| id | classid | contextid |
1 1 2
2 1 1
3 2 1
4 1 1
this will yields me the result by the use of an inbuilt library function moodle as
Array
(
[1] => stdClass Object
(
[classid] => 1
[classcnts] => 3
)
[2] => stdClass Object
(
[classid] => 2
[classcnts] => 1
)
)
I need the result in an array in the form of
Array(
[classid]=>[classcnts]
)
i.e
Array(
1=>3,
2=>1
)
So how can i arrange the available array to find the required array.
I am working in PHP
Thanks
try:
foreach($arr as $k){
$new[$k->classid] = $k->classcnts
}