mysql query giving incorrect result in for loop - php

The code belows gives me only 18 records
<?php
$result4 = mysql_query("select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries' GROUP BY Country ");
echo "<table width=880 align=center>";
echo "<tr><td colspan=4 style='font-family:Arial;'><b>European Region</b></td></tr>";
$num_columns4 = 4;
$num_rows4 = mysql_num_rows($result4);
$i=0;
while($row4 = mysql_fetch_assoc($result4)){
$results[$i] = $row4['Country'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows4/($num_columns4+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns4;$j++){
echo "<td width=220 style='font-family:Arial; font-size:12px'>".$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table>";
?>
while the select statement
select Distinct Country from trendsmtable where WHORegionAC='Europe -
all countries'
returns 22 rows while I execute it in mysql which is correct!
Please help me to found the error.

Well, you have an extra $k++ in there that you don't need:
$k++; // keep this one
}
echo '</tr>';
$k++; // remove this one
}
Edit
I've gone through your code and I've made some edits. Hopefully they'll clean your issue along the way:
// got rid of group by. With a select distinct, it isn't necessary
$result4 = mysql_query("select Distinct Country from trendsmtable where ".
"WHORegionAC='Europe - all countries'");
// a good practice is to always double-quote your HTML attributes.
echo "<table width=\"880\" align=\"center\">";
echo "<tr><td colspan=4 style=\"font-family:Arial;\">".
"<b>European Region</b></td></tr>";
$num_columns4 = 4; // where does 4 come from.
// $results was never initialized before.
$results = array();
while($row4 = mysql_fetch_assoc($result4)){
// This is generally thought of as "cleaner" than using an index.
// And since there cannot be more than, say, 220 rows, cleanliness
// should be a high-priority standard.
$results[] = $row4['Country'];
}
// mysql_num_rows rarely provides any major benefit at all.
$num_rows4 = count($results);
foreach( $results as $key => $val )
{
// This happens every time we fill all columns and need a new row.
if( !( $key % $num_columns4 ) )
{
// makes it so that after the first time this closes the prev
// row before starting a new one.
if( $key ) echo '</tr>';
echo '<tr>';
}
// insert nag about CSS
echo '<td width="220" style="font-family:Arial; font-size:12px">'.
$val.
'</td>';
}
echo '</tr></table>';

I think the PHP looks a little odd, it looks like you are looping from 0 to (22 / 5)
then in the inner loop 4 times.
The group by should not make any difference as you are doing a select distinct

Your SQL code in the PHP file contains a GROUP BY clause, which can reduce the number of rows returned, if you have a country more than once in the db.

Related

Populate 2 column HTML table with a single PHP result set

Please forgive me as I am beginner in PHP.
I am trying to populate 2 two column table with inventory information. With my current code, I have the below image:
I would like to have two stores next to each other in this table. i.e Store Number 2 and Store Number 7 on the table row in the table, then Store 10 and 11 on the same row, and so on. Below is the code I am using so far to achieve this:
global $wpdb;
$result = $wpdb->get_results(
$wpdb->prepare( "
SELECT STORE_NAME,REPLACE(STORE_NAME, ' ', '-') as STOREURL, INVENTORY, STORE_NUMBER FROM StoreInventory
WHERE SKU = %s",
$product_sku
)
);
if ($result){
echo '<table class=\'inventory\'>';
foreach($result as $row) {
echo '<tr><td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td></tr>';
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
The problem I am having is that I am looping through the record set row by row, and adding the data to each row. I have attempted to have a loop inside a loop, which will not give me the correct results.
Is it possible to split the result set into two multi-dimensional arrays and loop through each one separately then add them to the table? Can I call out a specific row with a counter within the loop?
Any advise or direction would be a great help.
A relatively simple approach would be to create a dummy variable to store the column. EX:
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</tr></table>';
Final answer based on ARubiksCube's answer:
if ($result){
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td \' width=\'50%\' ><div><a href=\'https://shopliquornl.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>' . $row->STORE_NAME . '</a><br/>' .$row->INVENTORY. ' on hand</div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}

how to loop depend <td> on table

I have problem with looping in table. i want to loop a <td>, when it reach 10 , it build <tr> automatically.
Here my code:
$sd=mysql_query("SELECT a.*,b.* FROM surat_jalan a inner join packing_list b on a.id_surat = b.identitas_packing WHERE b.identitas_packing = '$ben[id_surat]' ORDER BY netto_packing ASC");
while($pack=mysql_fetch_array($sd)){
$komapack = number_format($pack['netto_packing'],2);
echo"<td>$komapack</td>";
}
I am stuck on here and don't know what to do but I know how to use mod but " don't know how to loop it.
You can use a counter.
$i = 0;
echo "<tr>";
while($pack=mysql_fetch_array($sd)){
$komapack = number_format($pack['netto_packing'],2);
echo"<td>$komapack</td>";
$i++;
if($i % 10 == 0) // check
echo "</tr><tr>";
}
echo "</tr>";

What causes a query to exclude first record

PHP and MySQL:What causes a query to exclude the first record in a table:
for example i have a script like this:
$query = "SELECT * FROM cars WHERE car_name = 'BMW'";
$results = mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Vehicle Name:<th>";
echo "</tr>";
while($row = mysql_fetch_array($result)){
$name = $row['car_name'];
echo "<tr>";
echo "<td>$name<td>";
echo "</tr>";
}
echo "</table>";
All rows are returned except the first one.Please help a brother out folks.
Not an answer, but too long for a comment:
Let's take a peak at your table cars.
What does
$qs = array(
array('total #rows', 'SELECT Count(*) FROM cars'),
array('#BMW', "SELECT Count(*) FROM cars WHERE car_name='BMW'"),
array('#LIKE BMW', "SELECT Count(*) FROM cars WHERE car_name LIKE '%BMW%'"),
array('#car_names', "SELECT Count(*) FROM (SELECT distinct car_name as foo FROM cars) as bar")
);
foreach( $qs as $query ) {
echo $query[0], "<br />\r\n";
$result = mysql_query($query[1]) or die(mysql_error());
while ( false!==($row=mysql_fetch_row($result)) ) {
echo ' ', $row[0], "\r\n";
}
}
print if placed in your script instead of your posted code?
The output should be something like
total #rows<br />
6
#BMW<br />
2
#LIKE BMW<br />
3
#car_names<br />
4
BTW: the mysql_* extension is deprecated,
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
EDIT
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same name,
you must use the numeric index of the column or make an alias for the
column. For aliased columns, you cannot access the contents with the
original column name
You are using mysql_fetch_array and this is what it says in the documentation. I never use mysql* functions so I wouldn't have jumped to this type of conclusion quickly. Use mysql_fetch_assoc($results) and I'm 99% sure it will resolve your issue. The why this would be different is in the paragraph above from the documentation. I assume your first row is identical to at least 1 of the below rows. Which means it is very likely you're missing more than just the first one. May or may not be the case.
END EDIT
Add 4 things to your code.
echo "<tr>";
echo "<th>ID</th>"; // THIS
echo "<th>Vehicle Name:</th>"; // Add closing tags........
echo "</tr>";
echo mysql_num_rows($results); // THIS (compare this to your MYSQL output row count)
while($row = mysql_fetch_array($results)){ **THIS... you have $results set with query, but $result here*** make sure both are $results OR $result
$id = $row['YOUR_AI_ID']; // THIS
$name = $row['car_name'];
echo "<tr>";
echo "<td>$id</td>"; // THIS
echo "<td>$name</td>"; // Add closing tags.......
echo "</tr>";
}
Go go do now. Come back with results.

PHP syntax help on if statement

I'm trying to determine the right syntax from what I'm trying to do with MySQL. I'm basically saying that if a value in a certain column of a row of a table is equal to some session variables, I want to echo out info.
I have a table with subject, description and user. User is set by taking the current user's first name and last name and inserting it into the table under user. This is done by the following code:
$sql="INSERT INTO tbl_name (subject, description, user)
VALUES
('$_POST[subject]','$_POST[description]','$_SESSION[firstname] $_SESSION[lastname]')";
Then once I'm calling this data back out, I want to basically allow the user to delete content that they submitted themselves. The first step for me is to be able to display it in the table. I believe this is just syntax error, but I've confused myself now with how things are set up:
$sql = "SELECT * FROM tbl_name ORDER BY subject, description
LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME EXAMPLES:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if('$field->user' == '$_SESSION[firstname] $_SESSION[lastname]'){
echo '<td>You can delete this</td>';
}
}
I figured the $field->user would equal $_SESSION[firstname] $_SESSION[lastname] because that's how it was initially submitted to the table (without the '.' for concatenation).
Any help would be appreciated. Thanks!
EDIT
Here's the result of my table output code. The results are actually being display with $cell instead of from within the for loop I believe. I've added the if statement in after the but it doesn't seem to recognize echo "<td>".$field->user."</td>"; which makes me think that that is where the problem lies. What I would like to do is be able to add the if statement in a immediately after `echo {$field->user}"; to keep the code clean. I think I've confused myself thoroughly:
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME JOBS:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if($field->user == $_SESSION[firstname]." ".$_SESSION[lastname]){
echo '<td>You can delete this</td>';
}
else{
echo "<td>".$field->user."</td>";
echo "<td>".$_SESSION[firstname]." ".$_SESSION[lastname]."</td>";
}
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no jobs!';
}
I re-wrote the code in a way that was a little bit easier for me to understand (though maybe not the shortest way to do it):
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
It ended up working this way. If there's way to do this shorter then feel free to post it here otherwise thanks for the help!

Breaking up a long line of values in a box

The array $carry_over returns a really long list of entries, too long for my printout page. I would love to make it in such a way that after 4 entries, it breaks and goes to the next line and breaks at the next four entries until all entries are in.
How can i do this?
Thanks
echo "<table class=\"altrowstable\" bgcolor = gold >\n";
$count = 0;
echo "<tr align= \"center\">\n";
$carry_over = array();
$score_count = mysql_numrows($query8);
echo "<td>"."Failed: ";
if($score_count !== 0){
while ($row8 = mysql_fetch_assoc($query8)) {
echo "<th>".$row8['course_code']."</th>";
if ( $count == 7 ){
echo "</tr>\n";
echo "</table>";
}
}
}
Update : Now only the first 7 entries are covered inside the table tags, the subsequent ones are outside the table tags. How can i put them in the tabke tags?
Thanks
Not sure if this is what you are looking for, but you could try:
$count = 0;
echo "<tr>";
while ($row8 = mysql_fetch_assoc($query8)) {
echo "<th>" . $row8['course_code'] . "</th>";
$count++;
if(count == 4) {
echo "</tr><tr>";
$count = 0;
}
}
echo "</tr>";
It looks like you're using a table for list data. Instead of using a <table>, you should be using a <ul> with <li> for each element. This can then be styled so that each li has display: inline-block;, for example.
I cannot tell what the table looks like from the code above, but you can put an iterator in to count to four then wrap. You also may want to check out Wordwrap

Categories