Laravel 5.8 get tables belonging to a user - php

I am listing all tables in the DBthat are prefixed with the user->id + _ (eg: 2_my_table) like so:
$account = Auth()->user();
$tables = DB::select("SHOW TABLES LIKE '" . $account->id . "_%'");
This works and returns an array like this:
array:1 [▼
0 => {#577 ▼
+"Tables_in_mydb (2_%)": "2_country_list"
}
]
Why does it add the (2_%) search pattern to the Tables_in_mydb property?
This causes issues later when try and describe the tables like this:
if (count($tables)) {
foreach ($tables as $table) {
$table->columns = DB::select('describe '.$table->Tables_in_mydb);
$table->rows = DB::select('SELECT COUNT(*) AS count FROM '.$table->Tables_in_mydb);
}
}

Fixed like this. But still do not understand the original issue.
$tables = collect(DB::select('show tables'))->filter(function ($val) use (&$account) {
foreach ($val as $key => $tbl) {
$tbl_prefix = $account->id . "_";
$tbl_prefix_length = strlen($tbl_prefix);
if (substr($tbl, 0, $tbl_prefix_length) == $tbl_prefix) {
return $tbl;
}
}
});

You might have to go about it the long way.
By using get_object_vars, you can get the object values into an array. Then use array_values to get just the values:
$table_name_arr = array_values(get_object_vars($table));
This will provide with an array (0 => '2_country_list'), which you can easily get with $table_name_arr[0]
For a one-liner, use
$table_name = array_values(get_object_vars($table))[0];

Related

php recursive search and count of a value in json

I have a json feed with 6 objects all which have objects inside of them. I have an ID of something I am trying to search and count in another object.
if (isset($_GET['steamusr'])) {
$user = $_GET['steamusr'];
$myinv = 'http://steamcommunity.com/id/'.$user.'/inventory/json/295110/1/';
$content2 = file_get_contents($myinv);
$json2 = json_decode($content2, true);
$imgurlbase = 'http://steamcommunity-a.akamaihd.net/economy/image/';
foreach($json2['rgDescriptions'] as $i){
$item = $i['market_name'];
$icon = $i['icon_url'];
$fetchdata = 'http://steamcommunity.com/market/priceoverview/?appid=295110&currency=1&market_hash_name=' . urlencode($item);
$grab = file_get_contents($fetchdata);
$id = json_decode($grab, true);
$itemid = $i['classid'];
foreach($json2->rgInventory as $i2){
if($i2->$itemid == $itemid){
$ci = 0;
$count = $ci++ ;
}
}
All the data comes from rgDescriptions first, then rgInventory has the number of objects to count within it. The item ID comes from $itemid which I then need to search rgInventory for and then count the amount of matching id's in there from the set value $itemid.
My biggest issue is rgInventory has unique objects so I am trying to do a recursive/wildcard search of matching classid's.
The json structure can be found here: http://www.jsoneditoronline.org/?url=http://steamcommunity.com/id/fuigus/inventory/json/295110/1/
I think your code is correct in essence but you're not comparing the right things.
$json = json_decode($content2);
foreach ($json["rgDescriptions"] as $item) {
$num = 0;
foreach ($json["rgInventory"] as $inventory_entry) {
if ($inventory_entry["classid"] === $item["classid"]) {
$num += 1;
}
}
// do something with $num
var_dump($item["classid"] . ": " . $num);
}
The line:
if($i2->$itemid == $itemid){
Is bad, $i2->$itemid resolves to $i2->1107865473 which doesn't exist. I think you intended $i2->classid.
Error like this happen because you're using meaningless, abstract variable names. $i, $i2 and $content2, these are meaningless. You're also mixing the terms itemid and classid, it's easy to get confused.
Also, you're mixing bracket notation and object notation. Pick one and stick to it.

PDO prepare/execute the table and append WHERE's

I'm trying to do the following:
public function checkResult($table, $appends)
{
$append = null;
foreach ($appends as $key => $val)
$append = " AND `{$key}` = '{$val}'";
$result = $this->fetchObj("
SELECT *
FROM :cms_table
WHERE id :append
", array(
":cms_table" => $table
":append" => $append
));
return ($result ? true : false);
}
But I can't get this working because I don't know how to do this in PDO.
Also when I leave the :append my query isn't working either. It looks like I can't execute a table. When I change :cms_table to the cms_pages (table I need) it works correctly.
I couldn't find a thing about such query's in PDO. Anyone who can help me out?
Don't try to outsmart yourself.
You don't need no checkResult() function, as well as no other function of similar structure.
$sql = "SELECT 1 FROM table WHERE field = ? AND col = ?";
$found = $db->fetchObj($sql, array(1,2));
is all you actually need.

Passing array to like active record in codeigniter

I would like to pass array to like clause of active record in codeignter for that i have written the following:
$array_string = smart,intelligent,awesome;
$array_like = explode(',',$array_string);
and in model:
$this->db->like('topic',array($array_like));
but I am getting
Severity: Notice
Message: Array to string conversion
Any help or suggestion would be a great help.
See updated question here:
join not giving required result when using or_like codeigniter
You can't just pass an array to the like() function, it has to be a string. You need to apply a like clause for each of the keywords in the string.
You need to use or_like to match a record to either of the keywords, however, because if you just use like() each time, it will need to match all of the keywords due to the query being like LIKE "%smart" AND LIKE "%intelligent" etc. and that isn't what you require.
$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
foreach($array_like as $key => $value) {
if($key == 0) {
$this->db->like('topic', $value);
} else {
$this->db->or_like('topic', $value);
}
}
Try this way to avoid your problem of the rest of the where statement being ignored.
$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
$like_statements = array();
foreach($array_like as $value) {
$like_statements[] = "topic LIKE '%" . $value . "%'";
}
$like_string = "(" . implode(' OR ', $like_statements) . ")";
The value of $like_string will be (topic LIKE '%smart%' OR topic LIKE '%intelligent%' OR topic LIKE '%awesome%')
You can then use $like_string in the following way with ActiveRecord:
$this->db->where($like_string, FALSE);
Assuming you are using Codeigniter 2.1.4, as you can read in CodeIgniter active record documentation, you cannot pass the second argument as array in like function. You need to pass a string as argument.
$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
foreach ($array_like as $like)
{
$this->db->like('topic', $like);
}

Document exact matching

Let's say we have a following MongoDB-collection:
{id:1, data:"some_data"}
{id:2, data:"some_data"}
{id:3, data:"some_data"}
{id:4, data:"some_data"}
I also have an php-array with element "6" that is not in the collection
$q = [1,3,6];
If I query the collection like this:
$cursor = $db->col->find(['id' => ['$in' => $q]]);
I'm getting documents with id's 1 and 3
But I'd like to have an empty result because the id 6 do not exist in the collection,
how can I exact match the collection?
Can I do this with just one query?
If id is unique:
var result = db.col.find({id:{$in:q}});
if(result.count() == q.length) {
//handle result
} else {
//handle empty result
}
You can not do this just with one mongodb query, because it does not have such functionality.
Also I don't understand why exactly do you need this, you can achieve it doing something like this:
$q = [1,3,6];
$res = array();
$cursor = $db->col->find(['id' => ['$in' => $q]]);
foreach($cursor as $val){
$res[$val['id']] = $val['data'];
}
foreach($q as $val){
if (!isset($res[$val])) $res[$val] = ''; // to show that there is nothing in the results.
}
P.S. I have not tried this code, so there might be errors.

Parent Child Relationships PHP/MYSQL

I have a table like this:
id
name
parent_id
I then want to select certain rows based on their id, so something like this:
SELECT *
FROM TABLE
WHERE id IN ('1', '5', '8', '9', '35')
I want to, from this query, also show the parent/child relationship, like:
id parent
-----------
1 0
5 1
8 0
9 8
35 9
So the final output would look something like this:
1
--5
8
--9
----35
Do I do this outside of mysql, i have tried using arrays, but can't figure it out, or
Do I do it inside MYSQL, which i don't know how to do that either.
Here is what I was able to come with which seems to be working great.
PS-Sorry about the formatting, can't figure it out :( (fixed?)
I grab my parent_id and id from MYSQL and put it into an arraly where the array keys are the id's and the values are the parents, so with in the while loop for mysql, something like this: $testarray[$id] = $parent_id;
Then I run it through the functions below, and it orders it just how I need it.
function retrieveSubTree($parent, $myarray) {
$tempArray = $myarray;
$array = array();
//now we have our top level parent, lets put its children into an array, yea!
while ($child = array_search($parent, $tempArray)) {
unset($tempArray[$child]);
//now lets get all this guys children
if (in_array($child, $tempArray)) {
$array[$child] = retrieveSubTree($child, $tempArray);
} else {
$array[$child] = true;
}
}//end while
return (!empty($array)) ? $array : false;
}
function retrieveTree($myarray) {
$array = array();
$counter = 0;
foreach ($myarray as $key => $value) {
$child = $key;
$parent = $value;
//if this child is a parent of somebody else
if (in_array($child, $myarray) && $parent != '0') {
while ($myarray[$parent] != '' && $myarray[$parent] != '0') {
$newparent = $myarray[$parent];
$parent = $newparent;
}
if (!array_key_exists($parent, $array)) {
$array[$parent] = retrieveSubTree($parent, $myarray);
}
} else {
//now make sure they don't appear as some child
if (!array_key_exists($parent, $myarray)) {
//see if it is a parent of anybody
if (in_array($child, $myarray)) {
$array[$child] = retrieveSubTree($child, $myarray);
} else {
$array[$child] = true;
}
}//end if array key
}//end initial in array
}//end foreach
return (!empty($array) ? $array : false);
}
$test = array(
'1'=>'15',
'2'=>'1',
'3'=>'1',
'4'=>'0',
'5'=>'0',
'6'=>'4',
'7'=>'6',
'8'=>'7',
'9'=>'2',
'10'=>'9'
);
print_r(retrieveTree($test));
Without changing your table structure, this requires recursion, which MySQL does not support. You'll have to do it elsewhere. You can write a recursive function in PHP to use, for example, breadth-first search to build your array. Here it looks like you are using parent_id of 0 to denote a top-level object. You can search over your results, and add to your array every object whose parent is zero, which will give you an array with 1 and 8. Then you can recurse: find all the results with a parent of 1, and add that as a subarray to 1; then find all the results with a parent of 8 and add those as a subarray of 8. Continue doing this for each level until you've run out of results.
As other posters pointed out, you can do this natively in MySQL if you can change the table structure.

Categories