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);
Related
$_SESSION['lines'] is populated from a textbox that a user pastes into. Before I do anything with the data, I want to run it through a filter to see if any of the values they've input are NOT in the database.
foreach ($_SESSION['lines'] as $q) {
$multiSupplierQuery = "SELECT distinct supplier from allparts where quotePartNumber = '$q'";
$multiSupplierResult = mysqli_query($con, $multiSupplierQuery);
while ($row = mysqli_fetch_array($multiSupplierResult)) {
$multiSupplier = $row['supplier'];
}
if (!multiSupplier) {
unset($_SESSION['lines'[]);
}
}
The crux of this revolves around this statement:
if (!multiSupplier) {
unset($_SESSION['lines'[]);
}
What I'm trying to say is: each time we cycle through this, if multiSupplier doesn't exist, remove this particular element from the array.
my unset syntax is wrong though... how do I make it right?
You probably want to add a $ to your if statement. Change
if (!multiSupplier) {
to
if (!$multiSupplier) {
Also, to unset from the $_SESSION you need a key. Try changing
foreach ($_SESSION['lines'] as $q) {
to
foreach ($_SESSION['lines'] as $key=>$q) {
and then
unset($_SESSION['lines'][$key]);
It's not your unset usage, you just have an unnecessary opening square bracket.
unset($_SESSION['lines'[]);
should be
unset($_SESSION['lines']);
And you'll be good to go.
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}
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 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.)