Select next column to right mysql? - mysql

If I have a variable in php like,
$var = 'aaa';
And my mysql database has 2 columns
| aaa | bbb |
Is there a way I can select bbb using $var, basically select the column next to $var on the right?

Use mysql_query("SHOW COLUMNS FROM {table}",$db) to get a list of columns and use that to figure out the name of the column next to aaa. You can then use that in further queries.
Implementing this results in something in the lines of (untested):
$columns = mysql_query("SHOW COLUMNS FROM {table}",$db) or die("mysql error");
if (mysql_num_rows($columns) > 0) {
while ($row = mysql_fetch_assoc($columns)) {
if ($prev == 'aaa') {
$nextcol = $row['Field']; // 'bbb' in this case
break;
}
$prev = $row['Field'];
}
}

Related

I want to separate values in mysql using join in codeigniter

My mysql table look like
ranks are rank1,rank2,rank3 on id 1
but i want to show like that
id 1 -> rank1
id 1 -> rank2
id 1 -> rank 3
My sql Query
$this->db->select('rank')->from('rank_restriction');
$data = $this->db->get();
$query = $data->result_array();
foreach ($query as $result) {
if (!empty($result['rank'])) {
$result['rank'] = explode('||', $result['rank']);
}
return $query
}

MySQL Query: Concatenate horizontally based on selected ids

Say I have a table 'table_name' with two columns like this:
table_name
------------
my_id | data
------|-----
id1 | 312
id1 | 523
id1 | 128
id2 | 239
id2 | 479
id2 | 121
id3 | 639
id3 | 429
id3 | 131
id4 | 473
id4 | 872
id4 | 662
id4 | 174
id4 | 272
I tried around a while and I now found a way to select the ids I want to use:
SELECT DISTINCT my_id from table_name WHERE (my_id REGEXP 'id[234]')
This gives me the ids 'id2', 'id3' and 'id4'. How would I formulate a query that gives me my desired output, based on the selected ids as below?
id2 | id3 | id4
---------------
239 | 639 | 473
479 | 429 | 872
121 | 131 | 662
NaN | NaN | 174
NaN | NaN | 272
If your table really only has those two columns and there is no related data that can be used to order the data column like you have shown, then there is no good way to achieve the ordering you're looking for.
Relational data doesn't have any intrinsic "order" to it, even if you've inserted that data in a particular order or displayed it in a certain way here. If your table really only has those two columns, it will be difficult to match the "first" id2 value with the "first" id3 value and so on to get to your desired output. We could potentially rank them in a query and match them based upon that rank (ascending or descending) or even provide some random order capability, but there is no documented (i.e. reliable) way to get the order that you've provided.
While a table does have a physical order to the underlying bits in storage, and some products allow you to access them via a physical rowid (Oracle), no RDBMS that I know of (including MySql) guarantees the order in which the rows will be returned unless an order by clause is used in your select statement. This is literally by design and is considered a "feature" that came out of E.F. Codd's research.
First make a function that select distinct of the id's
public function get_id_of_table_name() {
$sql = 'SELECT DISTINCT my_id ';
$sql .= 'FROM table_name ';
$query = $this->db->query($sql);
$result = $query->row();
foreach ($result as $key => $value)
{
$result->data = $this->get_data($result->my_id);
}
return ( $query->num_rows() ) ? $result : FALSE;
}
And create the second function that will gather all the data's base on what id's
public function get_data($my_id) {
$params = [];
$sql = 'SELECT data ';
$sql .= 'FROM table_name ';
$sql .= 'WHERE my_id = ? ';
$params[] = $my_id;
$query = $this->db->query($sql, $params);
$result_data = $query->result();
$data = [];
foreach ($result_data as $result)
{
array_push($data, $result->data);
}
return $data;
}
You can put a where clause in the first function if you want.
$sql .= 'WHERE my_id = ? ';
and add the params
$params[] = $my_id;
You can also add parameters my_id as array in the first function so that you can get what id you want to get
$id = ["id2","id3","id4"];
public function get_id_of_table_name($id) {
$params = [];
$sql = 'SELECT DISTINCT my_id ';
$sql .= 'FROM table_name ';
$sql .= 'WHERE 1 ';
foreach ($id as $my_id)
{
$sql .= 'OR (my_id = ?) ';
$params[] = $my_id;
}
$query = $this->db->query($sql, $params);
$result = $query->row();
foreach ($result as $key => $value)
{
$result->data = $this->get_data($result->my_id);
}
return ( $query->num_rows() ) ? $result : FALSE;
}

How to retrieve every combination of numbers from 2 columns

I'm trying to find a way to retrieve every combination of values from two columns in a table, where each combination matches a value in a third column.
Say part of the table looks like this:
products_id options_id options_values_id
1487 2 1
1487 2 61
1487 3 60
1487 5 52
My desired output, when working with products_id 1487, would be the following two strings:
2-1, 3-60, 5-52
2-61, 3-60, 5-52
I've got the impression that those strings would need to be assembled recursively, but I ran into trouble trying it that way because not every products_id has the same options_ids, or the same number of them.
Edited to add: I've tried variations of a couple of the solutions below, but to no avail. I think I should have been more descriptive.
I'm trying to have it retrieve every combination of unique options_id and its corresponding options_values_id. (In other words, not every single possible combination of numbers from those two columns.) Options_id represents product options like "color" and "size," and options_values_id represents choices of those options, like "red" or "small." So I'm trying to come up with every possible combination of options for a given products_id. In the example above, there are two possible option combinations for that item-- "2-1, 3-60, 5-52" and "2-61, 3-60, 5-52".
Join the table against itself for each distinct option.
Do a select first to retrieve the number of options.
$tables = array();
$rs = mysql_query(
'SELECT DISTINCT options_id FROM table WHERE products_id = '.$id);
while ($row = mysql_fetch_row($rs)) {
$tables[$row['options_id']] =
'SELECT options_values_id FROM table WHERE products_id = '.$id.
' AND options_id = '.$row['options_id'];
}
mysql_free_result($rs);
Then, for each option, join it in as a separate table in your query. Do not include any joining clauses comparing values, just join every record against every other record.
$sql = 'SELECT ';
$count = 0;
foreach ($tables AS $id => $query) {
if ($count++) $sql .= ', ;
$sql .= 'table_'.$id.'.options_values_id AS value_'.$id;
}
$sql .= ' FROM ';
$count = 0;
foreach ($tables AS $id => $query) {
if ($count++) $sql .= ', ';
$sql .= '('.$query.') AS table_'.$id;
}
Finally, execute that query. Each row will contain one column per options_id. There will be one row per unique combination of values.
or for a mixed, php/sql approach, try using that SQL query:
SELECT products_id, options_id, options_values_id WHERE products_id = '$var_with_product_id';
fetch the results into an array, say $results:
$pairs = array();
foreach($results as $result) {
// build array with pairs (array_push to avoid overwriting)
array_push($pairs, array( $result['options_id'] => $result['options_values_id'];
}
// a bit extra complication, as array_push adds e.g. [0] => array( options_id => options_values_id ) :)
$pairs = array_values($pairs);
// check for double options_id
$found_double_options_id = false;
do {
// check for duplicates... use a lot of array functions
} while (count($pairs) && $found_double_options_id);
"Every combination" is the Cartesian product:
SELECT DISTINCT e1.options_id, e2.options_values_id
FROM Entity e1, Entity e2
WHERE e1.products_id = 1487 AND e2.products_id=1487

mysql - finding string from array

Database table:
id| p1 | p2 | notes
1 | 1 | a | cat, mouse, dog
2 | 1 | a | cat, horse, dog
I now need to run a query that selects the row where "notes" does not contain a string defined in the $exclusions array. I have tried the LIKE '%mouse%' operator, but that gave an error.
$exclusions = array ("mouse");
if($row['p1'] == 1 && $row['p2'] == "a" && $row['notes'] not like '%mouse%') {...}
Thank you.
Looks like you are doing the logic in a mix of PHP code and sql. To do it in php, you can do
!strstr($row['notes'], 'mouse')
That says "If there is no occurrence of "mouse" in $row['notes']"
The ! will make it return true if there is no occurrence.
if($row['p1'] == 1 && $row['p2'] == "a" && $row['notes'] not like '%mouse%') {...}
This is not MySQL syntax. It looks like PHP, and in PHP you can not use LIKE. Try a string comparison operator like strstr. http://php.net/manual/en/function.strstr.php
Mysql Style
A query to get all rows without mouse could be this:
SELECT * FROM `tablename`
WHERE `notes` NOT LIKE '%mouse%';
Or to get the exclusions from a php array:
$condition = "WHERE ";
$first = true;
foreach($exclusions as $ex) {
if(!$first) $condition .= " AND "; // or use OR
$condition .= "`notes` NOT LIKE \"%$ex%\"";
$first = false;
}
$complete_query = "SELECT * FROM `tablename` $condition;";

Loop through an array to unset a known value and implode to sql

I have two set of arrays in different MYSQL table. This what I want to do
What I Want TO Do
TABLE_ONE connect to the table.
get the value we want from session_id
THEN get the array associated with the value (session_id)
explode the array to get individual values.
NOW::::: - GO TO TABLE_TWO
TABLE_TWO Go straight to the first value from array (TABLE_ONE)
Explode the array associated with it.
Delete the number that's equal to the session_id
_____________________________________________________
And so fort....
More visual explanation below:
session_id = 4
TABLE_ONE:
id array1
1 4
2 1
3 2,5
4 1,3,4,5
5 4,5
TABLE_TWO:
id array2
1 4,6,9,2
2 3,7,8,2
3 7,12,4,9
4 1,5,4,8
5 3,6,12,3,5,4
So, because session_id = 4, we go to TABLE_ONE id 4. The array of id-4 is 1,3,4,5.
So now we know 4 can be found in id 1,3,4,5 of TABLE_TWO
We should now explode TABLE_TWO's array and delete 4 from there array. Implode the array and save the new value to database.
THIS IS WHAT I HAVE DONE - it would delete only '4' from them id-3 and delete all the values in id-4. Please help!!
$SESSION = 4;
$depSQL = mysql_query("SELECT array1 FROM TABLE_ONE WHERE id='$SESSION' LIMIT 1");
while($row=mysql_fetch_array($depSQL)) { $depARRAY = $row["array1"]; }
$explodedDEP = explode(",", $depARRAY);
foreach ($explodedDEP as $key1 => $value1) {
$stSQL = mysql_query("SELECT array2 FROM TABLE_TWO WHERE id='$value1'");
while($get=mysql_fetch_array($stSQL)) { $stARRAY = $get["array2"];}
$explodedST = explode(",", $stARRAY);
foreach ($explodedST as $key2 => $value2) {
if ($value2 == $SESSION) {
unset($explodedST[$key2]);
}
}
$newST = implode(",", $explodedST);
$sql = mysql_query("UPDATE TABLE_TWO SET array2 ='$newST' WHERE id='$value2'");
}
exit();
Please help!!! I'm really struggling on it.
I have tried it for hours now and i havent really got any where.
I think the problem is with the inserting to database.
Please help.
You can avoid one loop by using the array1 in your second SQL directly since it is already a comma seperated list.
Try this:
EDIT: Updated the code after testing.
$SESSION['ID'] = 4;
$depSQL = mysql_query("SELECT array1 FROM TABLE1 WHERE id='".$SESSION['ID']."' LIMIT 1");
while($row=mysql_fetch_array($depSQL))
{
$depARRAY = $row["array1"];
}
$stSQL = mysql_query("SELECT id, array2 FROM TABLE2 WHERE id IN ($depARRAY)") or die("Query Error");
while($get=mysql_fetch_array($stSQL)) {
$stARRAY = $get["array2"];
$id = $get["id"];
$explodedST = explode(",", $stARRAY);
foreach ($explodedST as $key2 => $value2) {
if ($value2 == $SESSION['ID']) {
unset($explodedST[$key2]);
}
}
$newST = implode(",", $explodedST);
echo $id . " " . $newST . "<BR/>" ;
$sql = mysql_query("UPDATE TABLE2 SET array2 ='$newST' WHERE id='$id'");
}
exit();
$SESSION is an array you can not assign value like this $SESSION = 4;
assign value like this
$SESSION['id'] = 4;
if ($value2 == $SESSION['id']) {