php foreach not iterating - php

$email is the name of a table in my database. When I execute the mysql query in phpmyadmin, I correctly get two casenums, 1 and 3.
However, when I try to loop through the array, echo $caseNum."<br>"; prints
1
1
instead of
1
3
The code:
$_SESSION['caseNums'] = mysql_fetch_array(mysql_query("SELECT `casenum` FROM `$email`"));
$_SESSION['cases'] = array();
foreach($_SESSION['caseNums'] as $caseNum) {
echo $caseNum."<BR>";
}

That's to be expected. mysql_fetch_array() returns a SINGLE row of data from your query, with dual string+integer keys.
In other words, you're printing out the value retrieved from the first row of data only, and printing it twice because it was duplicated in the returned array.
You need:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_row($result)) {
$_SESSION['caseNums'][] = $row[0];
}

Related

SHOW TABLES not returning correct items in array

I have multiple tables named like so MOM2016, MOM2017, MOM2018.
When i run query in phpmyadmin
SHOW TABLES LIKE 'MOM%'
it returns 3 items as expected.
BUT!!!! When i run in php, my code seem to give me only 1 item in the array (first one only MOM2016).
$sql = "SHOW TABLES LIKE 'MOM%'";
$result = $conn->query($sql);
$dbArray = $result->fetch_assoc();
echo "DEBUG:".count($dbArray);
This give:
DEBUG:1
My php code is wrong? Pls help.
If you want to get all the results at once,
$dbArray = $result->fetch_all();
echo "DEBUG:".count($dbArray);
Iterate through your fetch resource
$dbArray = array();
while ($row = $result->fetch_assoc()) {
$dbArray[] = $row;
}
print "DEBUG: " . count($dbArray);

Understanding fetch_assoc()

I am trying to understand how/why fetch_assoc works the way it does.
I have the following piece of code:
$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray); //print_r 1
while($row = $results->fetch_assoc()){
print_r($row); //print_r 2
}
The query returns 3 rows from a table.
Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?
Thank you.
Lets try to understand your code and how it works:
$results = $connectToDb->fetch("SELECT * FROM customer");
A variable $results has a collection of rows which are returned by a query. The size of the collection can be from 0 to n.
$resultsArray = $results->fetch_assoc();
This line fetch the first element from the collection. If the collection is empty it will return NULL.
while($row = $results->fetch_assoc()){
}
It can be decoupled in the following steps:
Calculate $row = $results->fetch_assoc() and return array with elements or NULL.
Substitute $row = $results->fetch_assoc() in while with gotten value and get the following statements: while(array(with elements)) or while(NULL).
If it's while(array(with elements)) it resolves the while condition in True and allow to perform an iteration.
If it's while(NULL) it resolves the while condition in False and exits the loop.
I think it useful:
function get_posts(){
$posts = array();
if ($result = $mysqli->query("SELECT id, post_userid, name, lang, country, post_image, post_date, post_date_updated FROM posts ORDER BY `post_date` DESC ;")) {
while ($row = $result->fetch_assoc())
{
$posts[$row['id']] = $row ;
}
} else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
return $posts;
}
in your case, if you want to print 3 rows each by each, you need to call this $result->fetch_assoc() as a three times.
for example, when you call the first time first row will be fetched and removed from array list. then 2 rows remain now.
in Second call second row will fetched and removed from array list.then 1 row remain now.
so you can call 3 times because you have a 3 rows. it will give null value if you call fourth times.because array list is empty now.
now come to the while($row = $results->fetch_assoc() this also do the same job which we discussed above.

Separating mysql fetch array results

i have a mysql table the contains an index id, a data entry and 10 other columns called peso1, peso2, peso3...peso10. im trying to get the last 7 peso1 values for a specific id.
like:
$sql = mysql_query("SELECT * FROM table WHERE id='$id_a' ORDER BY data DESC LIMIT 0, 7");
when i try to fetch those values with mysql_fetch_array, i get all values together.
example:
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'];
}
i get all peso1 values from all 7 days together. How can i get it separated?
They will appear all together because you are not separating them as you loop through them.
for example, insert a line break and you will see them on separate lines
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'] ."<br />";
}
You could key it as an array like so
$myArray = array();
$i = 1;
while($line = mysql_fetch_array($sql)) {
$myArray['day'.$i] = $line['peso1'];
$i++;
}
Example use
$myArray['day1'] // returns day one value
$myArray['day2'] // returns day two value
It's not clear what you mean by "separated" so I'm going to assume you want the values as an array. Simply push each row field that you want within your while loop onto an array like this:
$arr = array();
while($line = mysql_fetch_array($sql)) {
$arr[]=$line['peso1'];
}
print_r($arr);//will show your peso1 values as individual array elements

mysql_fetch_row not returning full array

I am attempting to loop through rows in MySQL with the following code. Unfortunately, the mysql_fetch_row function is only returning the first row of my query (I confirmed this with print_r). When I use mysql_num_rowsit returns the correct number of rows for that query(2). Any idea why mysql_fetch_row is returning only the first row?
$query = 'SELECT firstName FROM profiles WHERE city="Phoenix" and lastName ="Smith"';
$result = mysql_query($query);
$row = mysql_fetch_row($result);
print_r($row); //This returns only 1 array item: Array ( [0] => John)
$a=mysql_num_rows($result);
print_r($a); //This returns 2
I have also run the same query in MySQL and it returns both rows ("John" and "Jim").
Thanks for the help.
Just perform mysql_fetch_row twice (or in a loop). By definition (if you read the documentation) it returns only one row at once. So:
while ($row = mysql_fetch_row($result)) {
var_dump($row);
}
You want to put it in a while loop:
while ($row = mysql_fetch_array($result)) {
$firstName = $row['firstName'];
echo("$firstName<br />");
}
What this does is for each result (row) it finds, it fetches the data you want and displays it. So it gets the first result, displays the name, loops back to the top, fetches the second result, displays that name and so on, then once you have no more results that match the query criteria, the while loop is ended.
PHP accesses the SQL Results in order of how they're buffered. You'll need to run a loop to access all the contents.
If you wish to load everything into an array:
$allRows=array();
while($row=mysql_fetch_assoc($result) {
$allRows[]=$row;
}
You can use any of the following one:
while ($row = mysql_fetch_array($result))
{
echo $row['firstName'];
}
or
while ($row = mysql_fetch_assoc($result))
{
echo $row['firstName'];
}
or
while ($row = mysql_fetch_object($result))
{
echo $row->firstName;
}

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories