MySql Loop through a column to form concatenated string - php

I am new to SQL and PHP. I have a requirement where the end user enters text in an HTML form, which I am storing in MySQL db. Later I query all the tables in the db which has the user data to obtain concatenated strings.
For a clearer understanding here is an image of my data and the desired result: Click for Image
Right now I am able to concatenate only one string based on a specific id with this query:
select group_concat(text order by T.did separator ' ') as TTT
from (
select l.dimgroupid as did, d.*, l.dimlevelid as id, l.dimlevelvalue,
concat(d.dimensiontext," ",l.dimlevelvalue) as text
from dimensionlevel l
join dimension d on d.dimensionid = l.dimid
join dimensiongroup g on g.groupid = l.dimgroupid) as T
where T.id=0;
which gives me the result
| TTT |
--------------------------------
| A 20 year old Man is Fresher |
I know I can use a loop on id, but the problem is the ids are not fixed.
Note: There can be "n" number of dimensions and levels.
Here is an SQL Fiddle of the data I am trying to query: SQL Fiddle

I have edited your query to get what you wanted..
select did as groupid, group_concat(text order by dimensionid separator ' ' ) as TTT
from (
select l.dimgroupid as did, d.*, l.dimlevelid as id, l.dimlevelvalue, concat(d.dimensiontext," ",l.dimlevelvalue) as text
from dimensionlevel l
join dimension d on d.dimensionid = l.dimid
join dimensiongroup g on g.groupid = l.dimgroupid
) as T
group by id;
I hope this helps you...
UPDATE :
using php..
$sql = "SELECT `dimensionid`, `dimensiontext`, `dimensiondescr` FROM `dimension`";
$dimensions = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='age') ";
$ages = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='sex') ";
$sexes = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='experience') ";
$experiences = mysqli_fetch_all (mysqli_query($con, $sql));
foreach ($ages as $age) {
foreach ($sexes as $sex) {
foreach ($experiences as $exp) {
foreach ($dimensions as $dimension) {
$putage = "";
$putsex = "";
$putexp = "";
if($dimension[2]=="Age"){
$putage = $age[0];
}elseif($dimension[2]=="Sex"){
$putsex = $sex[0];
}elseif($dimension[2]=="Experience"){
$putexp = $exp[0];
}
echo $str = $dimension['1']." ".$putage.$putsex.$putexp." " ;
}
echo "<br>";
}
echo "<br>";
}
}

Related

I get a NULL value from var_dump when assigning a variable to an array in my select query

I have written a SELECT Query to concatenate a person's name and email address. I then want to echo this string.
Here is the code:
$sqldiv = "Select concat(p1.display_name, " - ", p1.user_email) AS Contact FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
If I use this SELECT QUERY it works:
$sqldiv = "Select p1.display_name FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
The only difference is that I am using concat. If I run the SELECT Query through SQL I get the output in a single string, which I assume is correct to set $div as an array.
What am I doing wrong?

How to append String with comma in php

I have one loop for appending some strings to a variable. I need a best way of doing same. Currently I am pushing everything to an array then I implode it with comma. Is there any other best way of doing the same? Here is my code
$getDataProduct = "SELECT pm.*,crm.id sub_id, crm.name sub_name FROM `cp_reference_master` crm
LEFT JOIN product_master pm on crm.parent_id = pm.category
Where crm.mode = 'item_type_subcat' AND pm.id = ".$data['id'];
$logger->debug("Get Product From Product Master for ".$data['id']);
$logger->trace("Query: ".$getDataProduct);
$result = $db->func_query($getDataProduct);
//echo '<pre>'; print_r($result); echo '</pre>';
foreach($result as $details){
$result[0]['sub_ids'] = $details['sub_id'];
$result[0]['sub_names'] = $details['sub_name'];
}
In my query I am getting 3 or 4 rows. except sub_id and sub_name everything is same. I need to append this sub_id and sub_name and put it in first row of sub_id and sub_name
Not sure this is the correct place your problem is but I will give it a try.
foreach($result as $details){
$result_ids .= "," . $details['sub_id'];
$result_sub_names .= "," . $details['sub_name'];
}
This will create a comma first so you need to clear that with:
$result_sub_names = substr($result_sub_names,1);
$getDataProduct = "SELECT pm.*,crm.id sub_id, crm.name sub_name FROM `cp_reference_master` crm
LEFT JOIN product_master pm on crm.parent_id = pm.category
Where crm.mode = 'item_type_subcat' AND pm.id = ".$data['id'];
$logger->debug("Get Product From Product Master for ".$data['id']);
$logger->trace("Query: ".$getDataProduct);
$result = $db->func_query($getDataProduct);
$sub_ids = '';
$sub_names = '';
foreach($result as $details){
$sub_ids = $sub_ids.', '. $details['sub_id'];
$sub_names = $sub_names.', '. $details['sub_name'];
$result[0]['sub_ids'] = $details['sub_id'];
$result[0]['sub_names'] = $details['sub_name'];
}
Now Every thing int the $sub_ids and $sub_names, no need to implode array with comma.

how to sent the ANY operand mysql

So I have a two tables users (IDN,RoP) and search_info (IDN, Location, Age) (IDN - is a key column )
I need collect and count the rows from database which have a correct type(RoP) and correct information (Location and Age).
so php :
$location = $_POST['location'];
$age = $_POST['age'];
$type=$_SESSION['type'];
so then I make mysql code...it is doesn't select raws but it is count them. I know that query is not used anymore, but I used it for educational purpose.
$search_result= mysql_query("
SELECT COUNT(a.IDN)
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
$search=mysql_fetch_array($search_result);
So as you can see the code is working but here the staff. I sent the location 1, 2 or 3 , otherwise 0. So if location == 0 I would like to grab from database rows regardless location (in other words - ANY location). Similar with age. is it possible realize on MYSQL? How to change variable that MYSQL grab any location?
AND the last question in code. I'm trying to select requirement data, but have problem to output them. so how to print this out?
$search_result= mysql_query("
SELECT COUNT(a.IDN), a.IDN, b.location, b.age
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
i=0;
while ($search=mysql_fetch_array($search_result))
{
$ar_result[] = $search; // some how I get only first row not all of them
$i++;
}
First:
<?php
$location = (int) $_POST['location'];
$age = (int) $_POST['age'];
$type=$_SESSION['type'];
$and_where = array();
if( $age )
{
$and_where [] = "b.Age = '{$age}'";
}
if( $location )
{
$and_where [] = "b.Location = '{$location}'";
}
if( ! empty( $and_where ))
{
$and_where = ' AND ' . implode( ' AND ', $and_where);
} else {
$and_where = '';
}
$sql = "SELECT COUNT(a.IDN) ".
"FROM users AS a LEFT JOIN info_search AS b ".
"ON a.IDN = b.IDN Where a.RoP='{$s_type}'" . $and_where;
?>
Second:
$search_result= mysql_query("
SELECT COUNT(a.IDN) as cnt, a.IDN, b.location, b.age
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
i=0;
while ($search=mysql_fetch_array($search_result))
{
$ar_result[] = $search ['cnt']; // some how I get only first row not all of them
$i++;
}

How to retrieve data from multiple tables using a PHP form?

I want to retrieve data from multiple tables using dot operator/join where arguments are passed from an HTML/PHP form.
HTML CODE
<input name="rollno" type="text" placeholder="Roll Number" required>
<input name="submit_view_details" type="submit" value="Proceed">
PHP CODE
if(isset($_POST['submit_view_details']))
{
$rollno = (int) $_POST['rollno'];
$query = "select * from table1, table2 where table1.{$rollno}=table2.{$rollno}";
$result=mysqli_query($connection,$query);
}
In the browser if enter the input 1 and echo this query then it looks like follows:
select * from table1, table2 where table1.1=table2.1
and no row is fetched despite of having data in the table(s).
it only works if the query looks like follows:
select * from table1,table2 where table1.rollno=table2.rollno
However, in that case it fetches all the rows but I need only the row of the rollno that user entered in the above mentioned form.
I am just not able to work this out. Help would be much appreciated. Thanks!
Use the AND keyword to specify the rollno.
SELECT * FROM table1, table2 WHERE table1.rollno = table2.rollno
AND table1.rollno = {$rollno};
You could probably use the keyword JOIN instead like this :
SELECT * FROM table1 NATURAL JOIN table2
WHERE rollno = {$rollno};
You need joins
take a reference of joins from here,
i am sure it will help
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
You should use join like this
$query = "SELECT tbl1.*, tbl2.*
FROM tbl1
INNER JOIN tbl2 ON tbl1.id = tbl2.id
WHERE tbl1.column = value ";
foreach ($pieces_2 AS $value) {
$pieces_3[] ="(CONCAT_WS('|',$presql2) like '%$value%')"; //concat all columns from one table
}
$serch_jyouken = implode(" and ",$pieces_3); // for multiple keywords
$result1 = mysqli_query($connection, "select p.p_no from pfr_data p where (" .$serch_jyouken .")");
$res1 = array();
while($r1 = mysqli_fetch_array($result1){
$res1[] = $r1['p_no'] ; //fetch primary key from table and store it into array
}
foreach ($pieces_2 AS $value) {
$pieces_4[] ="(CONCAT_WS('|',$presql3) like '%$value%')"; // same as above
}
$serch_jyouken1 = implode(" and ",$pieces_4);
$result2 = mysqli_query($connection, "select p2.p_no from pfr_mod_inform p2 where (" .$serch_jyouken1 .")" );
$res2 = array();
while($r2 = mysqli_fetch_array($result2)){
$res2[] = $r2['p_no'];
}
$res_mrg = array_merge($res1 , $res2); //merge array
$result = implode("','",$res_mrg ); // array to sring
$sql5 = $presql ." from pfr_data p where p.p_no in ('$result') order by p.section_p,p.status,p.no";

Output mysql result as an array of the form (column name => possible values for column name)

I have database such as
I want to create an associative array such that each att_name value is associated with its possible values from att_value:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
What is the best way to achieve this?
While it is easily possible to do this simply by selecting the results you want and iterating them in PHP to create the data structure you want, you could sub some of the work out to MySQL with GROUP_CONCAT():
$query = "
SELECT att_name, GROUP_CONCAT(att_value SEPARATOR ',') AS values
FROM table_name
GROUP BY att_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']] = explode(',', $values);
}
print_r($array);
Of course, this only works if your values will never contain the character (or sequence of characters) you use for the SEPARATOR in the MySQL query, so the safer pure-PHP way would be:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
Try below:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
This way :
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
Will give you something like that :
item att_name att_value
-----------------------------
books height 150 mm<!>250 mm
books price rs:20<!>Rs:20
books size 15 pg<!>30 pg<!>60 pg
books width 300 mm<!>400 mm
You have to explode the result from att_value by a <!>. I use this <!> so it highly impossible to have a value inside att_value with this. If you think you would someday use this, take another separator. Example : [{--}], _SEPARATOR_, [_-CUT-_], etc. Something you are sure at 100% you won't use a choice but always as a separator to split the text.
So example :
$SQL = 'SELECT item, att_name, GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value FROM table GROUP BY att_name';
$Query = mysql_query($SQL) or die('MySQL Error : '.mysql_error());
while($Assoc = mysql_fetch_assoc($Query)){
$Assoc['att_value'] = ($Assoc['att_value'] != '' ? explode('<!>', $Assoc['att_value']) : NULL);
print_r($Assoc);
}

Categories