Multiple Select Statements - php

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.

Related

split option with delimiter | into n-options in 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.

Pick a row with a specific index in a foreach loop

I want to output all image files of a specific productid. What is the right syntax to output the image path for row 1, row 2, row 3 etc? I can not find it.
$sql = "SELECT *
FROM images
WHERE productid = $productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
if($rs['imagepath']){
if($index == 0){
echo $imagepath[0]; // <---What is the right sytax of this?
}
}
if($rs['imagepath']){
if($index == 1){
echo $imagepath[1]; // <---and this?
}
}
if($rs['imagepath']){
if($index == 3){
echo $imagepath[2]; // <---and this?
}
}
The whole point of a foreach loop is it goes once through each select as "index". so you shouldn't have to worry about making an if-statement for each possible row, just make the statement once, and it will happen on each and every iteration
$rows = [];
$sql = "SELECT *
FROM images
WHERE productid = productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
$rows []= $rs;
}
echo $rows[0]['imagepath'];
aren't we missing the fetch function?
`
$select = $db->prepare($sql);
$select->execute(array());
$i = 0;
while($row = $select->fetch()) {
echo $i . ' '. $row['imagepath'] . '<br>';
$i++;
}
?>
`
--
addendum:
I now understand you only want one, or some, of the images to be shown.
Would it not be easier then, to only select that/those images?
SELECT imagepath
FROM images
WHERE productid = productid
AND someid = 3
or if no "someid" is present:
SELECT imagepath
FROM images
WHERE productid = productid
LIMIT 2,1
That would avoid the need to loop through may be 100 records to only use the 3th.

Replace occurrence of string with image in PHP+SQL loop?

This PHP code takes records from my database and displays them. Basically, I want every occurrence of the string "cross" (lowercase only) to be changed to an image that is on my web server.
Records currently look like: crossJohn Doe. So when it appears on the page, it should replace cross with the img and keep the rest.
The code:
$sql = "SELECT DisplayName, LastName, FirstName FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
$result = mysqli_query($conn, $sql); // query
if (mysqli_num_rows($result) > 0) { // as long as the query returns something, do the calcs.
$array = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ // whule there are results, put them in the array
$array[] = $row; // add the row in to the results (data) array
}
$counter = (count($array)); // find the amount of items in the array
$divisorCount = ceil($counter/2); // column count
$forEachCount = 1;
//loop while there are items in the array
foreach ($array as $row){
$forEachCount++; //increment counter
// naming logic
if (empty($row['DisplayName'])) { // if there is no DisplayName
if (empty($row['FirstName'])) { // show lastname
$block[] = "<div class='block'>".$row['LastName']."</div>\n";
}
else { //show first + last if no display name
$block[] = "<div class='block'>".$row['FirstName']." ".$row['LastName']."</div>\n";
}
} else { // show display name
$block[] = "<div class='block'>".$row['DisplayName']."</div>\n";
}
if($forEachCount > $divisorCount){ //insert each record into a "block"
$forEachCount = 0;
end($block);
$key = key($block);
$block[$key] .= "</div><div class='column'>"; // insert all "blocks" into a css div
}
}
unset($row,$key,$forEachCount,$divisorCount); //cleanup
//insert the div and populate it with the blocks
$output = "<div class='tableContainer'>
<div class='column'>".implode($block)."</div>
</div>";
print_r($output); // display all of it!
unset($array,$block);
}else{echo "<p>There are no donors in this category.</p>";}
using the REPLACE mysql string function might be enough
$sql = "SELECT REPLACE(DisplayName,'cross','<img src=\"path/to/image\" />') AS `DisplayName`, REPLACE(LastName,'cross','<img src=\"path/to/image\" />') AS `LastName`, REPLACE(FirstName,'cross','<img src=\"path/to/image\" />') AS `FirstName` FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace
you can use mysqli_fetch_assoc instead of using mysqli_fetch_array and adding another argument to get only the associative one
while ($row = mysqli_fetch_assoc($result)) {
if (stripos('cross',$row['keyname']) !== false)
$row['keyname'] = str_replace('cross','<img src="path/to/image"/>',$row['keyname']);
$array[] = $row; // add the row in to the results (data) array
}

how to count duplicates values inside while loop using php

$query = "select * from tableitem";
$result = mysql_query($query);
$col = array();
while ($row = mysql_fetch_array($result)){
//they have computation here inside loop.
$amount = $value;
if($row['status']>3){ // base on the status only
if($amount>0){ //base on the computation
$count = $item;
// i need to count here the item before the grouping of duplicate item below.
if (!isset($col[$row['item']])) { // this is working for grouping the duplicate value
echo $row['item'];
echo $count; // count item
$col[$row['item']] = true;
}
}
}}
Sample output should be like this inside while loop if possible.
Item one 2
Item two 3
Item five 4
You can do that with sql not necessary php;
SELECT COUNT(*) as N,item
FROM tableitem
GROUP BY item
it will return duplicate items and you can check with n>1. And you can add more column for group.
$itemArray;
while ($row = mysql_fetch_array($result)){
if($row['n']>1){
itemArray[] = $row['item'];
}
}
print_r($itemArray);
If you increment array values using the keys you are trying to count:
$check = array();
foreach($values as $key => $value) {
if (isset($check[$key])) {
$check[$key]++;
} else {
$check[$key]=1;
}
}
var_dump($check);

query select * from table limit 0, 100, for every (even limit) echo something

i have a database wherein i echo anything i want but i want to echo something else every time the code echos 2 things. I actually tried foreach() function but im actually quite confused on how to use it with this kind of situation
here's an example:
$sql = "SELECT * FROM table ORDER BY ID DESC LIMIT 0, 100";
$rs = mysql_query($android_app_sort,$con);
while($row = mysql_fetch_assoc($android_app_q_sort))
{
echo $row['ID'];
<--FOR EVERY 2 echos's then ECHO SOMETHING-->
}
all help is appreciated
Like this:
for( $i = 0; $row = mysql_fetch_assoc($android_app_q_sort); $i++ ) {
if( ( $i % 2 ) == 0 ) {
print "Even row."
}
}
$sql = "SELECT * FROM table ORDER BY ID DESC LIMIT 0, 100";
$rs = mysql_query($android_app_sort,$con);
$iterator = 0;
while($row = mysql_fetch_assoc($android_app_q_sort))
{
$iterator++;
if($iterator%3 == 0) {echo 'something';}
echo $row['ID'];
}
use simple modulo operation, this will print every third row something.
You can use like below code
$i=0;
while($row = mysql_fetch_assoc($android_app_q_sort))
{
if($i%2 == 0)
{
echo $row['ID'];
}
$i++;
}

Categories