I'm putting values from the database inside a while into an array. Now I wan't to check - inside the while - if the next ID is the same as just outputed. If it isn't my thought is to put the ID inside the array.
Is there any possibility to do this? To check a the next output of a query in a while?
$result = mysql_query("SELECT * FROM $postmeta ORDER BY post_id ASC")
or die(mysql_error());
$basArray = array();
while($row = mysql_fetch_array( $result )) {
$innerArray[$row['meta_key']] = $row['meta_value'];
$basArray[$row['post_id']] = $innerArray;
// Above post_id I want to check if it is the same as the "next coming"
}
Greetings
I would usually just store the most recent ID in a variable, and check it at the top of the while loop. In pseudocode, like this:
$old_row_id = -1; // any value that can't legitimately appear
while ($row = fetch_array($result)) {
if ($old_row_id == $row['id']) {
// logic to follow if IDs are the same
} else {
// logic to follow if IDs are different
}
// logic to follow in either case, if any
$old_row_id = $row['id']; // update variable for the next run through
}
If you really do need to change the behaviour for a particular row according to what happens in the next row, I recommend that you actually effect that change in the following run through the loop, when you check the new row ID against the old one.
Alternatively, you can loop through the resultset twice: the first time putting the rows into a 2-dimensional array so that you can easily reference difference rows by number. Then the second time, you actually do whatever you wanted to do in the first place, and you can reference "the next row" by using [$i + 1] rather than [$i]. (Of course then you have to be careful about the final row, because then the offset [$i + 1] doesn't work.)
Related
$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if (it is 1st record){
echo "make orange juice";
}else{
echo "make all juice";
}
}
Let say output are 3 records from database "Zac", "Michelle", Andrew". "Zac" is the 1st record get from database, how to write the "if" statement to check if the records is 1st record or not?
First off, if the order of records returned matters, you must explicitly include an ORDER BY clause in your query to specify which column to sort results on. Otherwise, the order of rows returned is technically indeterminate.
To operate differently on the first fetched row than on later rows, you may simply call fetch() outside the loop first, then loop over the remainder. Each call to PDOStatement::fetch() will advance the rowset record pointer, so the while loop will only iterate the records after the one already retrieved.
// Fetch the first row from the rowset
$r3 = $q3->fetch(PDO::FETCH_ASSOC);
$level3downlines = $r3['member'];
// Do actions specific to 1st row before the loop
echo "make orange juice";
// Then fetch the remaining rows with a loop
// and perform the their actions in the loop.
// The rowset record pointer has advanced beyond the 1st row
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
echo "make all juice";
}
In practice, I don't often do operations while fetching rows unless the rowset is very large. Instead I would more likely retrieve all rows as an array where I can more easily perform array operations on the set.
// Get all rows
$all_rows = $q3->fetchAll(PDO::FETCH_ASSOC);
// Pull the first row off the set
$first_row = array_shift($all_rows);
// do whatever with $first_row
// Loop over the other rows
foreach ($all_rows as $index => $row) {
// Do whatever with $row
}
Instead of using array_shift() in that way, when using $index => $row in the foreach loop, you could also check $index == 0 to operate on your first row. You may find this more understandable.
foreach ($q3->fetchAll(PDO::FETCH_ASSOC) as $index => $row) {
// First row
if ($index == 0) {
// Do first row actions
}
else {
// Do common actions for remaining rows.
}
}
I'm not sure if I understood you correctly, but you want to do a special action for the first row,
$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
$first_row = true;
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if ($first_row){
echo "make orange juice";
$first_row = false;
}else{
echo "make all juice";
}
}
UPDATE: Michael Berkowski's answer is better and faster.
So, I'm trying to display an associative array generated from a table in my database. These are the steps I'm trying to accomplish:
Get result set from database that's already sorted in certain order based on a column(Ascending/Descending).
Add/Transfer/Append each record/row in the result set to another array. While in the process of appending, check if the array we are adding records has a value(based on a different column) similar to the record we are currently adding.
If the value we are checking for is already there, skip appending. If not, append the record and continue with the loop until the end of the result set.
This is the sample data I am working with, tbl_user_details:
Sample data
As you can see, it has been sorted in descending order based on the user_pos column. If you look at the user_id column, we have duplicate values. What I am trying to achieve is adding each record to an array and skipping the duplicate values based on the user_id column.user_id = 4 and user_pos = 7. Next will be ada with user_id = 2 and user_pos = 6. The next record which we are not going add is woz with user_id = 2 and user_pos = 5 because we already have someone with user_id = 2. So, we skip to adding ghopper who has user_id = 3 and user_pos = 4... and so forth. I think this example explains the flow of data I need displayed.
I've tried some simple code to get this done which it's clearly not working. Here is the snippet:
$query3 = "SELECT * FROM `user_details` ORDER BY `user_details`.`user_pos` DESC";
$user_set = mysqli_query($connection, $query3);
if (!$user_set) {
die("Database query failed.".mysqli_error($connection));
}
$user_arr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $user_arr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
}
The records that should be displayed are of aswartz, ada, ghopper and rasmusl. The rest are ignored. When I display the data in '$user_arr[]' using the foreach loop method, it still displays the whole data as it is on the table.
It will become multi dimensional array when you add row to array so you cant check user_id in it. There are many other solutions to check unique record but One simplest solution is to assign user_id as key then check key for duplication
while ($row = mysqli_fetch_assoc($user_set)) {
if (isset($user_arr[$row["user_id"]])) {
continue; // skip if we already have this value in array
}
$user_arr[$row["user_id"]] = $row;
}
Note: If you want unique records only then you can use DISTINCT in query
Use another $tempArr which will contain only user_id to in in_array, In you code you are checking user_id against array or whole row which is user details not just against user_ids
$user_arr = array();
$tempArr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $tempArr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
$tempArr[] = $row["user_id"];
}
Just wondering if anyone can help me with this problem...
I want to be able to check if a certain ID (user for example is logged on) The ID's of these users will be pulled from a table, and then fed into an array and then checked if it is in there.
However when I pull the data the if inarray() no longer works as it would if I just typed it in straight within the code instead of pulling it.
I want to pull approved ID's through so they can access a certain link essentially!
Any help would be appreciated! Thanks!
<?php
mssql_select_db("$ins", $con);
$result = mssql_query("SELECT ID FROM Event WHERE EventPublic LIKE 'Yes' AND EventDate >= GETDATE() -1 ORDER BY EventDate ASC ");
while($row = mssql_fetch_array($result))
{
$test = "". $row['ID'] .",";
}
$tests = explode(',', $test);
if (in_array("2, 48", $tests)) {
echo "WOO";
}
else
{
echo "BOO";
}
mssql_close($con);
?>
in array should be an actual array
in_array(array('2', '48'), $tests)
also, it would be better to put
$tests = array();
before the while loop, then change the code inside the loop to read
$tests[] = $row['ID'];
then you can do away with the '$tests = explode(...' line.
Your having the issue with your in_array test because you are comparing an array and with a string in the following line:
if (in_array("2, 48", $tests))
The above line checks if the string "2, 48" exist in the array. But the array will have 2 as one element and 48 as a separate element. To fix this you can search for each element individually with something like:
if(in_array('2',$tests) || in_array('48',$tests))
I'm trying to figure out the best way to do something like this. Basically what I want to do (in a simple example) would be query the database and return the 3 rows, however if there aren't 3 rows, say there are 0, 1, or 2, then I want to put other data in place of the missing rows.
Say my query returns 2 rows. Then there should be 1 list element returned with other data.
Something like this:
http://i42.tinypic.com/30xhi1f.png
$query = mysql_query("SELECT * FROM posts LIMIT 3");
while($row = mysql_fetch_array($query))
{
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else
{
print "<li>Add something here</li>";
}
You can get the number of items in the resultset with mysql_num_rows. Just build the difference to find out how many items are "missing".
There are three ways I can think of, get the row count with mysql_num_rows, prime an array with three values and replace them as you loop the result set, or count down from three as your work, and finish the count with a second loop, like this:
$result = db_query($query);
$addRows = 3;
while ($row = mysql_fetch_assoc($result){
$addRows--;
// do your stuff
}
while ($addRows-- > 0) {
// do your replacement stuff
}
If you dont find a row, Add extra information accordingly.
$query = mysql_query("SELECT * FROM posts");
for($i=0;$i<3;$i++){
$row = mysql_fetch_array($query);
if($row){
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else{
print "<li>Add something here</li>";
}
}
Assuming you store the rows in an array or somesuch, you can simply do some padding with a while loop (depending how you generate the other data):
while (count($resultList) < 3) {
// add another row
}
I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);