Selecting different items in a fetch array - php

When using mysql_fetch_array, i pass the array data to a separate variable. My question is how do i access the different items held in that array by their position?
Preferably i want to call each item in turn have a calculation run on that item and if the result is the lowest number so far, pass that data to a variable.
Any help is appreciated, thanks.
<?php
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
echo "<span>" . $postcode['postcode'] . "</span></br>";
}
?>
Instead of echo out all postcodes how would i define to only output the third item in the array

Solution 1:
You can display them with a foreach in the while:
foreach($postcode as $data) {
echo $data;
}
Solution 2:
You can call them by position (starts with 0):
$postcode[0]
$postcode[1]
$postcode[2]
...
Read more about array's : http://www.php.net/manual/de/language.types.array.php

When you call mysql_fetch_array, you are getting the results of the next row returned by your query. In this case, your query is returning a result set with one column, postcode, and many rows (presumably). Your while loop is just getting each row's postcode value and echoing it in a <span>.
EDIT: I have changed my code example in reponse to the OP's comment.
I am not really familiar with what it is you are trying to do, but hopefully my example makes some sense (you will have to fill in some blanks with your code). For one, I don't think you need to store the results from the database into one big array and then go through each record to determine the lowest distance. You are already looping through each record in your while loop, make use of it!
<?php
$inputcoords = //I assume that you already have the coordinates for the input postal code somewhere
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
$curpostcode = $postcode['postcode'];
$curcoords = //calculation/function/something that calculates the current coordinates from $curpostcode
$distance = //Haversine formula using $curcoords and $inputcoords (you'll have to figure this part out)
if (!isset($lowest) || $distance < $lowest) {
$lowest = $distance;
//optional: if you want to keep track of which postal code gave the shortest distance...
$lowestpostcode = $curpostcode;
}
}
//go on to use the calculated distances for something...
?>
Also, as a side note, mysql_* functions are deprecated. If at all possible, you should switch to mysqli or PDO.

Related

I am searching from a database. In the results It brings 3 rooms for a single hotel. This is displayed as 3 hotels in my android recyclerview

How do i filter an array list in php to skip one row that has already been added where one of its column value is repited.
I have tried using in_array to filter and array_exist
$getRoom = mysqli_query($con, $sql);
$json_array = array();
while($row=mysqli_fetch_assoc($getRoom)) {
if (in_array($row['hotel_name'], $json_array)) {
}
else {
$json_array = $row;
}
}and
echo json_encode($json_array);
I want hotel name and one of the rooms found
The code (as it is provided right now) is not actually adding a line to $json_array, it's just replacing the current value with the current row. $json_array = $row; needs to become $json_array = $row[];
The second issue is that in_array isn't going to recursively search the second level of array so it's never going to find $row['hotel_name']. I would recommend restructuring your arrays a bit (depending on how your downstream code is going to use them) to something more like this:
while($row=mysqli_fetch_assoc($getRoom)) {
$json_array[$row['hotel_name']][] = $row;
}
This will group your data so that each hotel is only listed once in the top level array but you keep all of the details about the various rooms. If you really only need the distinct hotel names then you should restructure your database query to only return unique values using a distinct clause.

How to find out automatically the numeric index of an specific MySQL column in PHP?

I´m new to PHP and SQL and it´s the first time I post here, hope I do it right =)
I need to find out the numeric index from an certain field in my database. Thing is I´m not done with the database structure yet, so for this specific field I´d like to have it automated so I won't have to change the code every time I add or remove columns.
I also need it to have BOTH index types so I can call the columns by name in part of the code and by index for automated parts of it.
I´ve managed to achieve the result I wanted trough an very ugly code, because all the array_search and array_keys I´ve tried didn´t work out for some reason.
Here is the snippet of my working but ugly code. Do you have an more elegant solution?
Thanks in advance for your answers, and for all I´ve learned so far from reading other peoples questions!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
Finding the numeric index:
$student = mysqli_fetch_array($dadosRes,MYSQLI_ASSOC) or die(mysql_error());
$numericIndex = array_search("cont1",array_keys($student));
Giving MYSQLI_ASSOC will force the query to fetch only the associative keys; otherwise it will give you both numeric and associative array.
PHP function, array_search in this case, requires the third parameter set to TRUE:
<?php
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes, MYSQLI_BOTH) or die(mysql_error());
$student_keys = array_keys($student);
$cont1 = $student_keys[array_search("cont1", $student_keys, true) - 1];
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$student[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$student[$i+2]."</li>";
echo "</ul></p>";
}
}
?>
MYSQLI_BOTH is used in the mysqli_fetch_array function because first the array is searched for the column name, then later the array is looped over with numeric indexes. This results in the $student array having integer 0 as the first element and therefore causing array_search to choke. Adding true as the third parameter causes a === comparison unchoking the function. :) (Explanation: PHP array_search consistently returns first key of array )

How do I insert values into an multidimensional-array, then show them?

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.
?>

Trying to get field data to fit into if inarray() check

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))

Get next value of MySQL statement inside while

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.)

Categories