I'm trying to figure out how I would do a foreach statement inside my while statement. As you can tell by this code, it will only submit 1 row out of the table, even though it selects all the rows. How would I make it select each row?
Code:
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"));
$num_rows = mysql_num_rows($q2);
while(count($num_rows) > $i){
echo "<div style='float:left;width:940px;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($q2[1])."</a><h2>".$q2[2]."</h2></div></div></div>";
$i++;
}
New Attempt:
$q2 = mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'");
$i = 0;
foreach($q2 as $s){
echo "<div style='float:left;width:100%;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($s[1])."</a><h2>".$s[2]."</h2></div></div></div>";
$i++;
}
Although now this doesn't display any rows.
$q2 = mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'");
$i = 0;
while ($s = mysql_fetch_array($q2, MYSQL_NUM)) {
echo "<div style='float:left;width:100%;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($s[1])."</a><h2>".$s[2]."</h2></div> </div></div>";
$i++
}
Just to be clear, your query, SELECT * FROMticketreplyWHEREticketid='$id' is most likely only selecting one row from the table. I'm assuming that the ticketid in your ticketreply table is unique. So there is only one row selected.
If I go with this assumption, then...
mysql_fetch_array fetches all of the columns from a single row returned by a query. Documentation on mysql_fetch_array can be found here.
I would recommend, before you dive right into outputting your HTML and styling, start first with some print statements of $q2, to see that it really contains what you expect it to contain, and has the structure that you expect it to have.
Try:
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"));
print_r($q2);
You should see that $q2 is an array that is both integer-indexed and also string-indexed (that is, it is also a hash where each column name in your table is a key). Let's restrict mysql_fetch_array so that it just gives us the associated array (the string-indexed part) and not the integers.
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"), MYSQL_ASSOC);
Now, you can access each element of $q2 as a key-value pair by the following:
foreach ($q2 as $column => $value) {
print "column name: $column\n";
print " value: $value\n";
print "\n";
}
If, instead, you don't care about the column names, and you just want an integer-indexed array of values, then you can do the following:
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"), MYSQL_NUM);
Then, you can use a regular for loop for iterating through your result...
for ($i = 0; $i < sizeof($q2); $i++) {
print "Value $i: " . $q2[$i] . "\n";
}
Once you get a good feel for what the structure of $q2 is, then you will probably feel pretty comfortable and confident outputting your HTML with values from $q2 embedded in the right place.
Related
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
while ($row = mysqli_fetch_array($r))
{
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2))
{
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID']=$row2['SpecID'];
$i++;
}
usort($ModDates); // <<< ??
$DeleteIDs[] = $ModDates[0]['SpecID'];
foreach ($ModDates as $ModDate)
{
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
?>
Hi I'm trying to Delete specifications from the product database (or at least get a list of ones to delete) where we have duplicates and we want to delete the oldest one.
So here I've 1) found a list of duplicate codes 2) Assigned spec id to each mod date 3) Sorted the mod dates to find the oldest*NOTE 4) Found a list of ids to delete by finding the id assigned to the first of the sorted array. 5) unsets the moddate array for the next set of duplicates
NOTE: I think solving this problem might have something to do with sorting the multidimensional array - this is the part that I'm fairly sure is wrong. If this wasn't a multidimensional array we would at least see the modification dates in order. At this point I COULD just do a search for product code and oldest (first in array) mod date which thinking about it now - would achieve the same result? Does it matter that the primary key will be lost - after all - all I need is to get rid of the product code with the older modification date.. it doesn't matter that we don't have the primary key?
P.S. I did see a post about sorting multi-dimensional arrays Here but I felt I should show you what I was doing in case somebody had a better suggestion?
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
That $a variable seems useless.
while ($row = mysqli_fetch_array($r)) {
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2)) {
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID'] = $row2['SpecID'];
$i++;
If $ModDates[] === $ModDates[$i], as you say, then write $ModDates[$i] in both assignments. $ModDates[] === $ModDates[$i]can be wrong, $ModDates[$i] === $ModDates[$i] cannot.
Moreover :
$ModDates[] = ...
$ModDates[$i]['SpecID'] = $row2['SpecID'];
Now, whatever has been assigned to $ModDates[$i] in the first line is gone, it's now an array with only one key : 'SpecId'.
}
usort($ModDates); // <<< ??
What does that comment mean ?
$DeleteIDs[] = $ModDates[0]['SpecID'];
You put only one value from the array into $DeleteIDs. Why ?
foreach ($ModDates as $ModDate) {
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
That foreach will iterate only once because the line right above unsets the array it's iterating over.
In case it's a mistake and you in fact wanted to unset $ModDate :
- That will teach you to use variables with names you can differenciate
- That wouldn't want anyway because $ModDate is a copy of an entry of $ModDates, not that entry itself. Unseting it changes nothing in $ModDates.
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
}
I added the two last curly brackets, I don't know if you pasted wrongly or if you simply forgot to put them in your code.
Hi I would like to compare two tables from two different databases.
Select from the first database
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
$row = mysqli_fetch_array($sql);
Select from the second database
$sql2 = mysqli_query ("SELECT * FROM employee");
$row2 = mysqli_fetch_array($sql2);
Then I compare the two table
if ($row['icnum'] == $row2['emp_ic'])
{
echo "Data already exist in both database.";
}
else
{
while ($row = mysqli_fetch_assoc($sql))
{
echo "<td align='center' height='30'>" . $row ['name'] . "</td>";
echo "<td align='center'>" .$row['icnum'] . "</td>";
}
}
But my problem is it only compares the first row in the database.
My output should only display the staff name that is not available in the other database. However, this is my output.
Based on the output it only compares the first row. So how do I change my code so that it compares the whole row. Please help me, thank you!
You're not looping through the results of the query. You're simply getting back the first row and going with that.
Ex:
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
This is returning a result set which you then need to use
$row = mysqli_fetch_array($sql);
to get the actual values. The problem comes when
$row = mysqli_fetch_array($sql);
by itself only gives you one row.
Solution 1
You must use code like this:
while($row = mysqli_fetch_array($sql))
{
//Do some comparison
}
Since you're going to have to loop through two different result sets, you're going to have to do a loop within a loop, build an array of results and then loop through the results afterwards to output your HTML.
Ex:
while($row = mysqli_fetch_array($sql))
{
while($row2 = mysqli_fetch_array($sql2))
{
if ($row['icnum'] == $row2['emp_ic'])
{
//add to array of equal data
}
else
{
//add to array of not equal data
}
}
}
foreach($array as $not_equal_or_equal_data)
{
//output your desired HTML
}
Solution 2
Depending on what you actually care about, you could do a sql statement like this
$sql = "
SELECT
*
FROM
emasa.staff_detail AS sd
JOIN db2.employee AS e
ON sd.icnum = e.emp_ic";
This would return all the rows where those two columns were equal
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 a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.
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;