What causes a query to exclude first record - php

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.

Related

How can I group values from a database using <td> and rowspan?

So, I am reading some values from a database. Such as 'result', 'team', 'league' from a database. I am trying to display, in a <table>, results of the specific team grouped by league, something like this:
That is assuming my database contains the following data:
result1 team1 league1
result2 team1 league1
result100 team1 league2
result101 team1 league2
result88 team1 league2
I have tried a lot of stuff and yet I can't get it to work. Also, the league cell must have a rowspan equal to the number of results detected in the specific league. This can be done with mysql_num_rows, but I don't know exactly where to place it. So how can I get this table to work? Thanks a lot!
Groupng the output by league is a simple matter of doing a break-sort on the results of your query. Since your question doesn't
include your table schema, or any php code, I've made some assumptions about your table, and will leave opening the connection to
your DB, and executing the sql statement to you.
$qstr = "SELECT league, team, event
FROM table
ORDER BY league, team, event";
// Execute query, get results into associative array $allrows
$league = "";
$col1 = "";
$col2 = "";
echo "<table>\n";
foreach($allrows as $rowno => $row) {
if($league != $row['league']) {
if($league != "") {
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
}
$league = $row['league'];
$col1 = $league;
$col2 = "";
}
$col2 .= $row['team']." got ".$row['event']."<br />\n";
}
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
echo "</table>\n";
I have try'd some way and it worked for me I hope it works for you...
Look at the code:
$db = new PDO('mysql:host=localhost;dbname=you_dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT league, result, team FROM matches_info';
$stmt = $db->query($sql);
echo "<table border=\"1\">";
while($row = $stmt->fetch()){
echo '<tr>
<td rowspan="3">'.$row['pcid'].'</td>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].' </td></tr>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].'</td></tr></tr>';
}
echo "</table>";
It is very basic you can Add more functions to improve the functionality of it.

How to get record count of an array of objects in PHP

I'm trying to display the total number of records returned from my mongo 3.4 database. For this particular query, the results should be 380 but it's showing 14489. I'm sure it's something simple that I'm missing / forgetting about PHP
Here's the code: (including some debug statements about the type of variable I'm dealing with)
$numrecords = count($records);
echo"<BR><font color=red>".gettype($records)."</font>";
echo"<BR><font color=red>".sizeof($records)."</font>";
if ( $numrecords > 0 ) {
echo "<tr><td colspan='5'><h3>Record Count: ".$numrecords ."</h3></td></tr>";
echo "<tr><th>PH Number</th><th>Department</th></tr>";
foreach ( $records as $rec ) {
if (!empty($rec->department)) {
echo "<tr>";
echo "<td>". $rec->phnum . "</td>";
echo "<td>". $rec->department . "</td>";
echo "</tr>";
}
} //end for
} else {
echo "<tr><td colspan='5'>No matching data</td></tr>";
}
It says the object type is 'array'. I've been playing with count() vs. sizeof()
Any tips would be appreciated.
So it shows the correct number of rows in the table, but the count shows more than what's in the displayed table?
Try to use msqli_num_rows after your query
Here's an example below, you'll have to change it to your needs since you didn't provide your query code
$sql = "SELECT * FROM table_name WHERE datarow='$datarow'";
$result = mysqli_query($conn, $sql);
//this is where you count the number of rows returned from this query.
$count = mysqli_num_rows($result);
If this doesn't work, there's a problem with your query not meeting the specifications that you desire.

Display table results

I am trying to display results from a database onto my site. I have one entry in the database, and the result of that entry should be a "1". However, when I run the following code, it returns "1111111111111..." and continues to load ones. If there are 4 entries, I want the results to be displayed like:
1
2
3
4
I have looked around on this forum and others but cannot find anywhere where somebody had the same problem, and my code looks similar to the others. What did I do wrong?
functions.php:
$sqlgroup = mysql_query ("SELECT groupid FROM groups");
$grouprow = mysql_fetch_array ($sqlgroup);
Settings.php:
<?php while( ($row = $grouprow))
{
echo "<tr>";
echo "<td>".$row['groupid']."</td>";
echo "</tr>";
} ?>
First of all don't use mysql, use mysqli isntead:
$sqlgroup = mysqli_query ("SELECT groupid FROM groups");
while($row = mysqli_fetch_array($sqlgroup))
{
echo "<tr>";
echo "<td>".$row['groupid']."</td>";
echo "</tr>";
}

PHP: Can't Get Oracle Table to Display on Page

This is probably a really obvious error. Anyway, some details:
I have an oracle database that I need to extract data from to populate a table on a PHP page. The table is called Flowers and has Name, Price and Stock columns.
The part of the PHP code I'm having trouble with is this:
$titlevalue = Trim($_REQUEST['search']);
$query = "SELECT * FROM FLOWERS WHERE NAME = '$titlevalue'";
$stmt = OCIParse($connect, $query);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCIExecute($stmt);
The rest of my PHP works -perfectly- when using a different table on my database, which I did as a test. Just in case, this is the code that prints the query results (it's part of an HTML table, but you can ignore that):
while(OCIFetch($stmt)) {
echo "<tr valign=top bgcolor=#F7D4A3>";
$fg1 = OCIResult($stmt,"NAME");
echo "<td width=75>";
echo $fg1;
echo "</td>";
// Display values in column two.
$fg2 = OCIResult($stmt,"PRICE");
echo "<td width=75>";
echo ($fg2);
echo "</td>";
// Display values in column three
$fg3 = OCIResult($stmt, "STOCK");
echo "<td width=75>";
include($fg3);
echo "</td>";
echo "</tr>";
}
No matter what $titlevalue becomes, I just can't get results with this table. I have also tested it with a generic $query = "SELECT * FROM FLOWERS";, but that didn't produce anything either.
Could someone please lend a hand? :( It's been a very long night.
If I may, two things just to note:
1) you're using '$titlevalue', i think that will translate as ... $titlevalue in the query, and not its value
2) Its late ... have you checked that your table is called FLOWERS (case sensitivity)
I'd comment, but I dont have the rep to do so.
If this was helpful, please +1 or click the tickmark. I normally try and use the full format when doing sql queries
SELECT * FROM `table name` WHERE 'x'
... etc. where possible

mysql query giving incorrect result in for loop

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.

Categories