I tried to echo rows from mysql database. So in my code user can enter a value, and then program echoes table around the entered value. That part of the code works fine, but when I tried to echo entered values and corresponding row to the value, it somehow gave me first row. While I needed exact row, which I previously entered.
Here is my code:
$density = $_POST["density"];
$t = $_POST["t"];
$query = $pdo->prepare ("SELECT * FROM mytable WHERE "
."(Density >= '$density'-0.05 AND Density <='$density' +0.05) AND "
."(Temp >='$t' -2 AND Temp <='$t' +2) ");
if (!$query->rowCount() == 0) {
$query -> execute();
while ($results = $query->fetch(PDO::FETCH_ASSOC)){
echo "<table>";
echo "<tr><td>";
echo $results['Temperature'];
echo "</td><td">";
echo $results['Density'];
echo "</td><td>";
echo $results['DensityValues'] + $delden;
echo "</td></tr>";
echo "</table>";
}
}
So currently it prints the first row which is: Temp=>10, Density=>600, DensityValues=>658;
While I need to get values I have enterd and coresponding density value: Temp=>12, Density=>650, DensityValues=>678;
Related
This question already has answers here:
Show values from a MySQL database table inside a HTML table on a webpage
(9 answers)
Closed 1 year ago.
I am new at php and am trying to learn CRUD applications. For this part of the code I have a table set up in a database (mysql). I am trying to interact with the table. I want a user to login (that part works) and when they are logged in- I store a message in $_SESSION that says ie. 'success'. This lets me know the user is logged in. Not the problem. The second piece is that IF there are rows IN THE TABLE already (from previous sessions) I want to print out these rows in a table. If there are no rows I want to print out "No rows"
I am trying to use simple logic here where first I create the $row variable by doing a fetch that comes from a pdo object(also fine). If that row is TRUE ie. it exists, print the table. If that row is false, print no rows. However, I keep getting the whole table printed, say 5 times. Instead of the 5 rows in the table.
Also, I am not sure I am using the correct type of while () statement. Which right now reads,
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
And then I get the WHOLE table and all rows 5 whole times. fetch and PDO::FETCH_ASSOC are a bit unclear to me, and I am understanding the $row as either true or false.
$stmt= $pdo->query("SELECT make, model, year, mileage from autos");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( isset($_SESSION['success']) && $row == true ) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo ('<table border="1">'."\n");
echo "<tr><td>";
echo "Make";
echo ("</td><td>");
echo "Model";
echo ("</td><td>");
echo "Year";
echo ("</td><td>");
echo "Mileage";
echo ("</td><td>");
echo "Action";
echo ("</td></tr>");
echo "<tr><td>";
echo (htmlentities($row['make']));
echo ("</td><td>");
echo (htmlentities($row['model']));
echo ("</td><td>");
echo (htmlentities($row['year']));
echo ("</td><td>");
echo (htmlentities($row['mileage']));
echo ("</td><td>");
echo ('Edit'.'/'.'<a
href="delete".php?user_id='.$row['user_id'].'>Delete</a>');
echo "</td></tr>";
}
} elseif ( isset($_SESSION['success']) && $row == false ){
echo "No rows found";
}
I keep getting the whole table printed, say 5 times.
Because you're printing the whole table on each iteration of the loop:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo ('<table border="1">'."\n");
// etc.
Instead of checking whether the first row is true, check the row count:
$stmt= $pdo->query("SELECT make, model, year, mileage from autos");
$count = $stmt->rowCount();
if ( isset($_SESSION['success']) && $count > 0 )
Then output your table outside the loop and just output each row inside the loop:
echo ('<table border="1">'."\n");
// etc, output the table header
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
// etc.
echo "</td></tr>";
}
echo ('</table>'."\n");
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.
How to compare number of rows returned to a number and display message
I have a form with a drop down where people can select either a serial number or the name of a product and a textbox where they can type their search. I have the minimum length set to 1 because the serial numbers are minimum 1 digit and range up to 5 digits. Also, so that if they only know the first letter of the name it lists all the records starting with that letter. If they type the name of the product and only know the first letter of it, I'd like to display a message if they only type one letter in the name that says something like "Please try typing more than one letter." I can succesfully display this message, but if the number of records return is less than 5 it still displays.
I wrote code on the processing page for the form, so that it counts the number of rows returned and checks to see if it is greater than or equal to 5. I wanted to display this message if the search returns more than 5 records.
My question: How do I compare the number of records returned to the set number of 5 so that my message to go back and try a longer search (for the name of product) displays only when there are 5 or more records returned? It seems to display the message fine, but when <5 records are returned, it still displays the message.
my code processing page PHP code:
include "includeData.php";
$conn = mysqli_connect("localhost", $mysqlUname,$mysqlPW, $mysqlDB);
if (!$conn){
die('Could not connect: ' . mysqli_connect_error());
}
if (!empty($_GET['searchText'])){
$query = $_GET['searchText'];
$min_length = 1;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn,$query);
$sql = "SELECT * FROM machine WHERE `m_ipdb` LIKE '%".$query."%' OR `m_name` LIKE '%". $query."%'";
$qResults = mysqli_query($conn,$sql);
if (!$qResults){
echo "There was a problem!<br />";
die(mysqli_error($conn));
//added for best practice and consistency
}
echo "<table border='1'>";
while($row = mysqli_fetch_array($qResults))
{
echo "<tr>";
echo "<td>" . $row['m_ipdb'] . "</td>";
echo "<td><a href=\"details.php?m_ipdb=" . $row['m_ipdb'] . "&m_name=" . $row['m_name'] . "\">";
echo $row['m_name'];
echo "</a></td>";
echo "</tr>";
}
echo "</table>";
/*echo "<p>Number of rows returned: " . mysqli_num_rows($qResults) . "<br />";*/
$result = mysqli_query($conn,"SELECT COUNT(*) AS number FROM machine");
$num = mysqli_fetch_array($result);
$count = $num["number"];
if($count >= 5){
echo "<a href='search.php'>Return to Search Page</a><br />" . "And try searching for more than one letter in the name!";
}
else{
echo " ";
}
mysqli_close($conn);
}
}
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.
In mysql I have unix epoch time inserted and it needs to be displayed in calendar like table.
Every timedate should be echoed in row that represents that day.
Code that I have is this and it echoes 31 days in one column and all timestamps in one row. How to put them in correct day/row? Thank you.
<table>
<tr>
<td><strong>day</strong></td>
<td><strong>timestamp</strong></td>
</tr>
<?php
$sel = "select time from rv where id=$id";
$rez = mysql_query($sel) or die(mysql_error());
$n = mysql_num_rows($rez);
for($day=1; $day<32; $day++){
echo "<tr>";
echo "<td>$day.</td>";
while ($re = mysql_fetch_array($rez)){
$time_b = $re["time"];
$time_a = new DateTime("#$time_b");
echo "<td>";
echo $time_a->format('h:i:s');
echo "</td>";
}
echo "</tr>";
}
?>
</table>
Update:
Here is what I get now. And I need every date to be displayed in correct day/row
http://s3.postimg.org/nvmlf1mtv/test.jpg
Supposing you want your days from the database sorted from 1-31, your working the wrong way rond.
You first want to sort the values from the database, store by day and then display them.
Warning: I'm using your code for this answer, but DON'T USE mysql, use mysqli.
//make an array with all 31 days
$mydays=array_fill(1,31,array());
//loop the database results and fill the array
while ($re = mysql_fetch_array($rez)){
$day=date('d',$re["time"]);
//store the value in the $mydays array
$mydays[$day][]=$re["time"];
}
//now loop the days and display them
for($i=1;$i<32;$i++){
if(count($mydays[$i])<1)continue; //the is no data in this day
// else loop the data inside this day
foreach($mydays[$i] as $thisday){
echo "<tr>";
echo "<td>$i</td>";
echo "<td>";
echo date('h:i:s',$thisday);
echo "</td>";
echo "</tr>"
}
}