split option with delimiter | into n-options in php - php

I have a dropdown menu that gets populated by data retrieved from the db. it looks like this:
How can I split the options like GPOS RETAIL|INVENTORY STANDARD into separate options GPOS RETAIL and INVENTORY STANDARD. Also, how can I remove the repetitive options? I already have DISTINCT in my query but I guess the pipeline | affects this.
I've been tried the ff but I couldn't seem to get the logic I need to do what I need it to do
PHP:
$qry = "SELECT DISTINCT c.c_id, c.client_name, a.product
FROM client_list c
INNER JOIN activities a
ON c.client_name = a.client
WHERE c.c_id = '".$_POST['client']."' AND a.product IS NOT NULL
ORDER BY c.c_id";
$res = mysql_query($qry);
if(mysql_num_rows($res) > 0) {
echo '<option value="">SELECT SOFTWARE / HARDWARE</option>';
while($row = mysql_fetch_array($res)) {
echo '<option value="'.$row[2].'">'.$row[2].'</option>';
}
}
else {
echo '<option value="">No Record</option>';
}
One of what I've tried:
if (isset($_POST['client'])) {
$qry = "SELECT DISTINCT c.c_id, c.client_name, a.software_hardware
FROM client_list c
INNER JOIN activities a
ON c.client_name = a.client
WHERE a.software_hardware IS NOT NULL AND c.c_id = '".$_POST['client']."'
ORDER BY a.`software_hardware`";
$res = mysql_query($qry);
if(mysql_num_rows($res) > 0) {
echo '<option value="">SELECT SOFTWARE / HARDWARE</option>';
while($row = mysql_fetch_array($res)) {
$list = "";
$arr = explode("|", $row[2]);
if (!empty($arr)){
for($i = 0; $i<=$ctr; $i++) {
$list .= "<option value='$arr[$i]'>$arr[$i]</option>";
}
}
echo $list;
// echo '<option value="'.$row[2].'">'.$row[2].'</option>';
}
}
else {
echo '<option value="">No Record</option>';
}
}
I don't know where to go from here

You can use explode and foreach in PHP. You need some additional check, so you don't get empty lines. It's something similar like this:
if(mysql_num_rows($res) > 0) {
echo '<option value="">SELECT SOFTWARE / HARDWARE</option>';
while($row = mysql_fetch_array($res)) {
$names = explode("|",$row[2]);
foreach ( $names as $name ) {
if ( $name != "" ) {
echo '<option value="'.$name.'">'.$name.'</option>';
}
}
}
}
I've added the explode, which makes an array from the name string with the "|" dividers. After it you go through each element of the array, and if it's not empty, you add it as an option. Please not I've changed the reference of the rows to "$name".

for($i = 0; $i<=$ctr; $i++) {
...
}
should be
for($i = 0, $length = count($arr); $i < $length; $i++) {
that's all

You can use the following solution:
$items = [];
//get all items from database and explode the concat values.
while($row = mysql_fetch_array($res)) {
$items = array_merge($items, explode('|', $row[2]));
}
//get only the distinct items.
$items = array_unique($items);
//remove the emtpy items.
$items = array_filter($items);
//initialize the list.
$list = '<option value="">SELECT SOFTWARE / HARDWARE</option>';
//create the list of unique items.
foreach ($items as $item) {
$list .= '<option value="'.$item.'">'.$item.'</option>';
}
Explanation:
You can remove all duplicates by using array_unique. The pipes (|) are removed by using the explode function on the while loop.
You can remove all empty items by using array_filter (without callback).
demo: https://ideone.com/YWdKFU

First of all a little hint, that you shouldn 't use the mysql_* functions anymore. I know, that you said, that your company is using an outdated php version. But ... u know, that you 're working twice and they will pay a lot more money for development and so on.
Your for loop is the problem. You can solve unique values there and the $ctr variable you are using in your for loop was never defined.
$arr = $arr = explode("|", $row[2]);
$arr = array_unique($arr);
for ($i = 0, $length = count($arr); $i < $length; $i++) {
...
}
The array_unique function will sort out duplicate values in your array. After that the for loop iterates through the unique values of your array.
After all you should think about normalizing your database structure. It is not recommended saving values like "value1|value2|value3". Think about an one to many or a many to many structure. This will make life much more easier.

Related

Multiple Select Statements

I am trying to create a list of items in which every fourth item in the list is an item that is on from New York and On Sale. The rest of the items in the list are the items that are from New York no matter if they are on sale or not.
How can I properly use two select statements to break the list up into the order that I want? Below is what I'm using now. It creates a list of paragraphs but does not understand what the variables $article and $article2 are.
<ul>
<?
$sort = id;
$sql = "SELECT * FROM `Catalog` WHERE state = 'New York' and in_stock = 'yes' ORDER BY $sort";
$result = mysql_query($sql);
$sql2 = "SELECT * FROM `Catalog` WHERE state = 'New York' and sale_item = 'yes' ORDER BY $sort ";
$result2 = mysql_query($sql2);
$i = 0;
while ( $article = mysql_fetch_array($result) || $article2 = mysql_fetch_array($result2) ) {
if ($i == 0) {
echo '<li>This item number is on sale:'.article2[id]. '</li>';
$i++;
} else if ($i == 3) {
echo '<li>This item number is regular price'.article[id]. '</li>';
$i = 0;
} else {
echo '<li>This item number is regular price'.article[id].'</li>';
$i++;
}
}
?>
</ul>
Based on Dave's suggestion I'm trying it this way. But php still doesn't know how to interpret $itemsOnSale or $items.
<ul>
<?
$items = array();
$itemsOnSale = array();
$sql = "SELECT * FROM `Catalog` WHERE state = 'New York' AND in_stock = 'yes' ORDER BY $sort";
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) ) {
if ( $row['sale_item'] == 'yes' ) {
$itemsOnSale[] = $row;
} else {
$items[] = $row;
}
if ($i == 0) {
echo '<li>This item number is on sale:'.$itemsOnSale[id]. '</li>';
$i++;
} else if ($i == 3) {
echo '<li>This item number is regular price'.$items[id]. '</li>';
$i = 0;
} else {
echo '<li>This item number is regular price'.$items[id].'</li>';
$i++;
}
}
?>
</ul>
A better method would be to pull all items in a single query, store them in separate arrays, then reference them as necessary. In its current form your second query pulls sale items but doesn't check to see if they are in stock.
$items = array();
$itemsOnSale = array();
$sql = "SELECT * FROM `Catalog` WHERE state = 'New York' AND in_stock = 'yes' ORDER BY $sort";
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) ) {
if ( $row['sale_item'] == 'yes' ) {
$itemsOnSale[] = $row;
} else {
$items[] = $row;
}
}
Then construct your HTML list, pulling an array item from $itemsOnSale every 4th loop.
It looks like you omitted the $ in front of your variable names:
echo '<li>This item number is regular price'.article[id].'</li>';
should be
echo '<li>This item number is regular price'.$article[id].'</li>';
As an aside, it looks like you're trying to use what's called MARS -- Multiple Active Result Sets. Not all database drivers support this.
This is one of your problems:
while ( $article = mysql_fetch_array($result) || $article2 = mysql_fetch_array($result2) ) {
If a result is found from $result, the condition will be met and $article2 never gets populated. You should re-think the flow of your while loop.
You can try something like
while ( $article = mysql_fetch_array($result) && $article2 = mysql_fetch_array($result2) ) {
but this will finish once either $article1 or $article2 is empty. However you can add another while loop afterwards with just
while( $article = mysql_fetch_array($result) ) { // keep posting regular items }
but there's a chance you may have more sale items than regular items (and everything wouldn't get posted.) There's lots of ways to do this.
Also, you have to reference variables using $.
echo '<li>This item number is on sale:'.$article2['id']. '</li>';
You also had an extra closing bracket in your original code, check your parsing.

php - dynamic mysql_query in for loop from url array

I've looked for something similar on stack but nothing exactly as this.
I (think I) need to generate a unique MySQL query inside a loop as each iteration needs to look up a different table. the loop is from an exploded $_GET array.
The problem is creating a differently named mysql query based on the loop iteration. I've done it where the $var name is different but it doesn't work, I think because it is a string not a variable?
Any help appreciated
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
for ($i=0; $i<$tempCount; $i++)
{
/*'normal' database lookup
$check = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checks = array();
while ($row = mysql_fetch_assoc($check)) {
$checks[] = $row;
}*/
//here's where I'm trying to build a 'dynamic' lookup for each loop iteration
$checkTemp=$check.$temps[$i];
$checkTempArray=$check.$temps[$i].'Array';
$checkTemp = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checkTempArray = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$checkTempArray[] = $row;
}
}
If I understand correctly you're trying to SELECT * from all tables seperated by , in the $_GET["temps"]
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
$allResults = array();
for ($i=0; $i<$tempCount; $i++)
{
$checkTemp = mysql_query("SELECT * FROM _db_".mysql_real_escape_string($temps[$i]));
$allResults[$temps[$i]] = array();
while ($row = mysql_fetch_assoc($checkTemp))
{
$allResults[$temps[$i]][] = $row;
}
}
// Now for example $allResults["john"][3] contains the fourth row in the table _db_john
print_r($allResults["sally"][2]); // print the third row in _db_sally
Seems like a typo in your code
$checkTemp = mysql_query("SELECT * FROM db".$temp[$i]."");
either use
$temps[$i] or just $temp
$temp[$i] doesn't makes any sense
so your query should be instead
$checkTemp = mysql_query("SELECT * FROM db".$temps[$i]."");
EDIT:
for your array part you can use
$$temp = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$$temp[] = $row;
}

PHP Nested Loop. How on the second loop print items according to the id of the first loop?

I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.

Building a Json array with multiple parameters in Php

I managed to output the column 'resort' in the Json array, but I need 'country' too, as well as 'aantal'. Have no idea how to do that. Can someone please help me?
if ($numrows < 1 && strlen($sq) > 3)
{
$sql = "SELECT resort, country, COUNT(image) AS aantal FROM sx_cam
LEFT JOIN sv_orte ON sv_cam.res_id = sv_orte.res_id
WHERE sound=soundex('$sq') and (status < 1) GROUP BY resort order by aantal desc";
$result2 = mysql_query($sql) or die(mysql_error());
$numrows = mysql_num_rows($result2);
$suggest = 2;
}
$items = array();
while($row = mysql_fetch_assoc($result2)){
$items[$row['resort']] = $row['resort'];
}
foreach ($items as $key=>$value) {
echo strtolower($key)."|$value\n";
}
You're building the array the wrong way. Once you get the array right, it is as simple as making a call to json_encode
I'm not entirely sure how you want your json to look, but something like this should get you started
$items = array();
while($row = mysql_fetch_assoc($result2)){
//first we build an 'object' of the current result
$item['country'] = $row['country'];
$item['resort'] = $row['resort'];
//now push it on the array of results
$items[] = $item;
}
echo json_encode($items);
Once you get the above code working, you can tweak the PHP array to change the structure of the JSON to suit your needs.

Create PHP array from MySQL column, using auto_increment column as index

Much like this previous question, I wish to store a MySQL column in a php array (as opposed to storing by row). However, I want the array indexes to match those of the database's primary key.
For instance, for the following database:
id name
1 Joe
2 Mary
9 Tony
$name['9'] == "Tony"
Is such a thing possible?
Thanks!
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result)) {
$array[$row["id"]] = $row["name"];
}
yes,
$names = array();
foreach ($rows as $r) {
$names[$r['id']] = $r['name'];
}
A wrapper library can make this easier, e.g. with ADODb:
$array = $db->GetAssoc("select id,name from mytable");
Once I have my row results as arrays, I use this method:
function convertArrayToMap(&$list, $attribute, $use_reference=FALSE) {
$result = array();
for ($i=0; $i < count($list); $i++) {
if ($use_reference) $result[$list[$i][$attribute]] = &$list[$i];
else $result[$list[$i][$attribute]] = $list[$i];
}
return $result;
}
And the method call:
$mapOfData = convertArrayToMap($mysql_results, 'ID');

Categories