Currently, $selection outputs the following: MIN(Bale_ID), MIN(Incoming_Moisture) which is exactly what it should be outputting (they're names from another table). However, when I put $selection into the mysql_query $data1, it seems to just be reading the last value (MIN(Incoming_Moisture)) and only displays the results for that. How do I get the query to read the entire array of elements in $selection? Thank you!!
while ($row1 = mysql_fetch_array($fieldnames1)) {
$fields = $row1['fields1'];
$explode = explode(',',$fields);
if ($row1) {
for ($i=0; $i<$minrows; $i++) {
if ($i<$minrows-1){
$comma = ", ";
}
else {
$comma = "";
}
//$selection = "MIN(".$explode[$i].")".$comma;
//echo $selection;
$data1 = mysql_query("SELECT MIN(".$explode[$i].")".$comma." from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))");
$all1 = mysql_num_fields($data1); //return # of columns; for some reason is returning "1" right now.
while ($row2 = mysql_fetch_array($data1)) {
for ($col=0; $col<$all1; $col++) {
echo $all1;
echo "<td>Min: " . $row2[$col] . "</td>";
}
echo "</tr>";
}
}
}
}
echo "</table>";
Look at the order of operations in your code:
loop {
... fetch data ...
... assign results to $data1 ...
}
Nowhere in your loop do you output or save the results you've got in $data1, so each iteration of the loop overwrites the results of the previous iteration - in other words, only the LAST iteration's results will be stored.
you are running the query once per for loop cycle (1 field at a time) and since first ones yields in SQL error because of the trailin comma, these will not be echoed except the last one.
-- notice the error in first query
SELECT MIN(Bale_ID), from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
SELECT MIN(Incoming_Moisture) from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
use var_dump($selection) instead of echo $selection to see yourself
Related
This question already has an answer here:
How to get column names from PDO's fetchAll result?
(1 answer)
Closed 2 years ago.
The following code works perfectly well unless there is only one result, in which case only the <tr> containing the column names displays in the web page. Further, a search for the name 'Bracker' produces the result as described above but a search for 'Bra' works correctly while 'Brac' does not. The same does not apply to the name 'Dawe' which, if there is only one result, only appears amongst many others when a search for 'Da' is undertaken.
<?php
include 'connect.php';
if (isset($_POST['submit-keyword'])) {
$keyword = ($_POST['keyword']);
$qry = "SELECT * FROM Ely_NBR WHERE Founder LIKE ? ORDER BY DATE";
$stmt = $con->prepare($qry);
$stmt->execute(["%$keyword%"]);
print "<table>";
$result = ($stmt);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} // end foreach
print " </tr>";
//second query gets the data
$data = ($stmt);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
}
?>
You are using your first result row to display the column headings. When you call PDOStatement::fetch() it moves its internal cursor on the result set.
Therefore your loop to display the data starts printing the results from the 2nd row.
See PDOStatement::fetch() documentation: Fetches the next row from a result set.
If you want to get the column names you may want to look at:
PDOStatement::columnCount()
PDOStatement::getColumnMeta()
And print headings like this:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$columnInfos = $stmt->getColumnMeta($i);
echo '<th>' . $columnInfos['name'] . '</th>';
}
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
I have an array that I want to loop through. Using:
echo count($places);
I get a value of 2. Similar print_r the array gives 2 items.
However, when i run a for loop it seems to go through 4 iterations. This can be seen by adding echo $i to the loop, which produces an output of 0,1,2,3.
This is my code:
function enrichfromDB($places) {
$con = mysqli_connect("localhost","user","password","db1");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo count($places);
print_r($places);
for ($i=0 ; $i<count($places) ; $i++) {
echo $i;
$name = $places[$i]['name'];
$gettag = "SELECT Tag FROM PlaceTags WHERE Name = '$name'";
$data = mysqli_query($con,$gettag);
while($row = mysqli_fetch_assoc($data)) {
$tags[] = $row['Tag'];
}
$places[$i]['category_labels'][0][] = $tags[$i];
}
return $places;
}
count($places)
has a value of 2.
However, with the row of
$places[$i]['category_labels'][0][] = $tags[$i];
you are creating new elements inside your places array. Initially you had two elements, but some of the indexes you are using are not existent in the array, so they are created. Take a closer look at your array to solve your problem.
I am wanting to compare the next value in the array with my current value. If you look at my code I think you will see what I am trying to do but to explain I need only one picture to show if $row[2] is the same on the next loop thru.
My error start at // ERROR HERE in if Statement in the code below.
I am sure there is a simple solution to this but I don't know the proper name and could not find it in my searches.
-Disclaimer I am still an newbie at this please forgive me.
$connection = mysqli_connect($host, $user, $pass, $db);
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// create query
$query = "SELECT * FROM 1098";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
echo "<center>";
// ERROR HERE in if Statement
$nextrow = 1 + $row;
if ( $row[2] <> $nextrow[2]){
if ( $row[6] == "kit"){
$img ='<img style="width: 700px; height: 800px;" alt="Picture Not Found" src=" ';
$file = substr($row[2], -3);
$filepath='files/'.$row[6].'/'.$file.'_files/image001.png">';
echo $img.$filepath;
}
else
{
$img ='<img style="width: 700px; height: 280px;" alt="Picture Not Found" src=" ';
$filepath='files/'.$row[6].'/'.$row[2].'_files/image001.png">';
echo $img.$filepath ;
}
}
echo "</center>";
}
}
$nextrow = 1 + $row doesn't make sense. That would be attempting to add an integer to a database record, i.e. 1 + array('foo', 'bar', 'baz').
If you simply want to compare the current record with the previous record (on all loops after the first one) how about something like this:
while($row = mysqli_fetch_row($result)) {
print '<center>';
// If there is no previous record set (first record) or if the 2nd value is different.
if (!isset($prev_record) || $prev_record[2] != $row[2]) {
// ...
}
print '</center>';
// Assign the current row to a variable so that it's available on the next run.
$prev_record = $row;
}
Edit – here's an example of how you can get all records into a single array and then play with them:
$records = array();
while($row = mysqli_fetch_row($result)) {
$records[] = $row;
}
foreach ($records as $i => $record) {
$record; // current record
$records[$i-1]; // last record
$records[$i+1]; // next record
}
I would recommend splitting your data up into multiple tables, though, and using a cleaner approach.
$nextrow = 1 + $row;
Given $row is a row, this is not doing what you think it is.
If you want the nextrow from the query you have to fetch it.
If you can reverse your logic to use previous row , you could preserve that and compare it to the current row.
You could read them all into an array first, but on a big result set that would be expensive....
You could do two fetches, one to current row, one to next row,
And then add a lot of logic to deal with the first and last, and making current = next and fetching the next next :(
Or you could rework the query so it returned the data you need in one row.
You definitely can't do what you are trying to do though. There is no next row until you fetch. $row is an array of columns, there is no rows as in an array of rows.
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;