This question already has answers here:
How do I iterate over the results in a MySQLi result set?
(2 answers)
Closed 5 months ago.
I'm very new to PHP and I'm trying to get some code that someone else has written to work. As the title says it is only showing the first result when it should be displaying many and I have no idea how to sort it (even though I imagine it's quite simple!). The code is below:
$result = mysqli_query($connection, ("SELECT id FROM details where publicposition like '%$trimvar%' or familyorgname like '%$trimvar%' or commercialorgind like '%$trimvar%' ORDER BY id "));
if (!$result)
{
die('Could not run query');
}
echo "<h1>Your staff conflict search on <font color='#ff0000'>'$trimvar'<font color='#000'> returned <font color='#ff0000'>$rows<font color='#000'> results</h1>";
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
{
echo "<table style='width: 20%; border='0';'>";
echo "<tr>";
echo "<th> Record ID : " . $row['id'] . "</th><br/>";
echo "</tr>";
}
echo "</table>";
Any help on this would be hugely appreciated!
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch the next row
of a result set as an associative, a numeric array, or both
Try using mysqli_fetch_array inside a while loop to fetch one row at a time until the end is reached.
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<tr>";
echo "<th> Record ID : " . $row['id'] . "</th>";
echo "</tr>";
}
Related
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.
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.
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
This code is supposed to show the number of rows in the column "id". Why isn’t is working, when I go to the page it shows nothing except my HTML stuff?
<?php
$con = mysql_connect("quollcraft.net", "quollcr1_forum", "password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("quollcr1_hub", $con);
$result = mysql_query("SELECT id FROM table ORDER BY id DESC LIMIT 1 ");
echo "<table>";
while ($row = mysql_fetch_array($result)) {
echo "<td>";
echo "<center>";
echo '<p>' . $row ['id'] . ' total users<p>';
echo "</td>";
}
echo "</table>";
mysql_close($con);
?>
Your table name you are using are just table. I guess it should be changed to the real table name from which you want your data
table is one of the reserved word(s) in MySQL. You need to wrap them using backticks.
Like this..
$result = mysql_query("SELECT id FROM `table` ORDER BY id DESC LIMIT 1 ");
^ ^ //<---- Like that
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
Others have decent MySQL tips, but what happens when you view the source code? Because the HTML seems to be broken at best. This is the cleaned up version based on what I am seeing.:
echo "<table>";
echo "<tr>";
while ($row = mysql_fetch_array($result)) {
echo "<td>";
echo "<center>";
echo '<p>' . $row ['id'] . ' total users<p>';
echo "</center>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
You were missing the table row tags <tr> & </tr> as well as the closing </center> tag.
Looks like you are trying to retrieve the total count of ID(users) but you missed out the keyword count. You can modify either the query or you can get the count of $result. Hope this helps.
Coming back to my project after putting it down for a while: Cycling through a query.
I understand that the below code can be cleaned up (PHP usage and table arrangement) and that MySQL commands are deprecated. ( I am working on that part).
But I can't see why I can't make this work. The print_r() gives Resource ID #5 error. My results show 2 tables, each with identical results all from the same course. I am expecting 8 tables, each table with a different course.
Should I use a while loop? if so how? I realize this is elementary, but this is still all new to me so please be gentle.
<?php
include 'inc.php';
$varVeh=$_POST['Veh_num'];
$sql_course="select course_num from hc_course";
$results_course=mysql_query($sql_course);
print_R($results_course);
foreach(mysql_fetch_array($results_course) as $rc)
{
$sql_HiScores = "SELECT c.course_name as course, e.distance as distance, e.score as score, e.time as time, e.user as User from hc_entries e left join hc_course c on e.course=c.course_num WHERE c.course_num=$rc and e.vehicle=$varVeh ORDER BY course, score DESC ";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="select Veh_name from hc_vehicle_type where Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th> </tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
}
?>
mysql_fetch_array just returns one row of the results, not all the rows. Your foreach loop is just looping over the columns in the first row of results.
If you want to process all the results, you should write:
while ($rc = mysql_fetch_array($results_course))
Then inside your loop, you use $rc['course_num'] to get the course from that row.
But I don't understand why you need that first loop at all. You're JOINing the hc_courses and hc_entries tables in the first query inside the loop. Why don't you just use that same query, but without the c.course_num = $rc condition, so it gets all courses at once instead of doing them one course at a time? Loop over those results, and start a new table every time the course number changes.
Here's the query for that:
SELECT c.course_name as course,
e.distance as distance,
e.score as score,
e.time as time,
e.user as User,
c.course_num as course_num
FROM hc_entries e
JOIN hc_course c ON e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC
The PHP then looks like:
$last_course = null;
while ($row = mysql_fetch_assoc($results_HiScores) {
if ($row['course_num'] !== $last_course) {
// New course number, start a new table
if ($last_course !== null) {
// Close out last table, if any
echo '</table>';
}
$last_course = $row['course_num'];
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th> </tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
}
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
echo "</tr>";
}
if ($last_course !== null) {
echo "</table>";
}
And you shouldn't do the hc_vehicle_type query inside the loop. It doesn't use any variables that change during the loop, it's just looking up the name of $_POST['Veh_num']. Just do it once and reuse the result inside the loop.
try:
foreach(mysql_fetch_array($results_course, MYSQL_ASSOC) as $rc)
{
....
}
if second argument is not given, MYSQL_BOTH is assumed, so array has column name, and column number 0,1...,n . so you traversed result set twice (column name and column number)
RTMF : http://us1.php.net/manual/en/function.mysql-fetch-array.php
and The print_r() gives Resource ID #5 error this is not an error!. return value of mysql_query() is result set. it's just a Resource of PHP internal structure.
This question already has answers here:
PDO returning incorrect, but duplicate, data. Key's not in database.
(3 answers)
Closed 3 years ago.
The code below is producing duplicate <td> elements for each field. I am trying to produce a simple HTML table based on the results of a PDO query. Can anyone tell me why each field is being duplicated?
$data = $conn->query('SELECT * FROM students');
// Print results in a HTML table
echo '<table border="1" cellpadding="5">';
foreach($data as $row) {
echo '<tr>';
foreach ($row as $field) {
echo '<td>' . $field . '</td>';
}
echo '</tr>';
}
echo '</table>';
Thanks
It looks like you are using the PDO::FETCH_BOTH style.
This will produce an array where the entries are duplicated, once for the column name keys, and once for the integer keys.
See the following for details:
http://php.net/manual/en/pdostatement.fetch.php
$data = $conn->query('SELECT * FROM students');
echo "<table border="1" cellpadding="5">
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<td>".$info[column1] . "</td> ";
Print "<td>".$info[column2] . " </td></tr>";
}
echo "</table>