$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);
Related
I have a database table like
-----------------
| id | time |
|----|----------|
| 1 | 9am-10am |
| 2 | 11am-12pm|
and a PHP array
$times= array("8am-9am","9am-10am","10am-11am","11am-12pm","12pm-1pm","1pm-2pm","2pm-3pm","3pm-4pm","4pm-5pm","5pm-6pm","6pm-7pm","7pm-8pm","8pm-9pm","9pm-10pm");
My problem is, if the time is already in the database, the code shouldn't create a button with that value so I have the following foreach loop
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
foreach($times as $value){
while($row=mysqli_fetch_assoc($result)){
if($value!=$row['time']){
echo "<button>$value</button>";
}
}
}
But instead of showing all other values not 9am-10am and 11am-12pm instead it just shows two 8am-9am button
Try changing your code to this:
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
foreach($times as $value){
mysqli_data_seek($result,0); //reset the pointer to search from the first row every time
while($row=mysqli_fetch_assoc($result)){
if($value==$row['time']){
continue 2; //exits while loop and then skips foreach to the next $value
}
}
echo "<button>$value</button>";
}
Or the other solution (based on the other answer, so credits to JoSSte, but slightly modified, so it wouldn't have to iterate through the array):
$savedValues = array();
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$savedValues[$row['time']] = 1;
}
foreach($times as $value){
if(!isset($savedValues[$value])){
echo "<button>$value</button>";
}
}
It should work if you use in_array() and separate the loops, that way it will get more readable.
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
$resultTimes = array();
// Assign the DB values to an array
while($row=mysqli_fetch_assoc($result)){
$resultTimes[] = $row['time'];
}
// Check if values from $times are in the array, if not echo button
foreach ($times as $value) {
if (!in_array($value, $resultTimes)) {
echo "<button>$value</button>";
}
}
You are only running through the mysqli_resultset once, on the first instance of your foreach.
You need to rethink your logic. Fetch the mysql result outside your foreach, put the results in an array, and then use that array in a foreach instead of your while loop.
//first, fetch the rows from DB
$savedValues = array();
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$savedValues[] = $row['time'];
}
//then compare
foreach($times as $value){
foreach($savedValues as $svd){
if($svd != $value){
echo "<button>$value</button>";
}
}
}
NOTE: this is not optimal. as another comment states, you should consider in_array() or something similar to avoid loops in loops
I'm trying to combine two tables from a database, and based on my first one, I want to retrieve some value from the other one, and add them to an array.
Here's my problem:
My first database looks like that:
FIRST TABLE:
id, credit_type, association_name, address, city, province, postal_code, country, cycle_type, cycle_begin, cycle_months
My second database instead looks like that:
SECOND TABLE:
id, association_id, designation_name
The id in my first table matches the association_id in my second table so I don't need an INNER JOIN.
My approach is the following:
<?php
public function my_function()
{
$sql = ee()->db->select('*')->from('first_table')->get();
$data['database'] = [];
if ($sql->num_rows() > 0)
{
foreach($sql->result_array() as $row)
{
$id[] = $row['id'];
$data['database'][] = $row;
}
}
foreach ($data['database'] as $key => $value) {
$association_query = ee()->db->query("SELECT * FROM second_table WHERE id = $id");
foreach($association_query->result_array() as $row_two)
{
if ($association_query->num_rows() > 0)
{
$data['database'][$key]['associations'][] = $row_two['designation_name'];
}
}
}
return ee()->load->view('index', $data, true);
}
?>
The sintax ee()->db->select('*') is a prepared statment from expression engine and it's equal to SELECT * FROM first_table (sanitaized).
So as you can see, I try to pass the value $id, which is an array, to my query. The thing is that as soon as I push the value like that $id[] = $row['id'] I create a nice array, but when I loop through my foreach loop, it multiplies my array in many other arrays so I'm not able to run my query, even if I'm technically in a foreach loop.
Plus, as soon as I try to push the result of my query in my array, let's say changing the id in a static id for instance id=3, I obtain a really weird result, like so many arrays repeated with 1 value, 2 value, 3 value and so on, when I'd like to push my key 'association' only where it is presented in the other table.
If you won't do it on SQL, at least don't execute the second query so many times.
<?php
public function my_function()
{
$assocs = array();
$data = array('database' => array());
$association_query = ee()->db->query("SELECT * FROM second_table");
if ($association_query->num_rows() > 0) {
foreach($association_query->result_array() as $row) {
$assocs[$row['association_id'][] = $row['designation_name'];
}
}
$sql = ee()->db->select('*')->from('first_table')->get();
if ($sql->num_rows() > 0) {
foreach($sql->result_array() as $row) {
$id_check = $row['id'];
if (isset($assocs[$id_check])) {
$row ['associations'] = $assocs[$id_check] ;
}
$data['database'][] = $row;
}
}
return ee()->load->view('index', $data, true);
}
?>
Regards
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
}
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.
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.