Why PHP foreach display query post two times? - php

When I try to query some content from certain table under certain column, The echo result shows two values, one with the key 0 and other with the key name of the column.
My code is like this :
$query = "select id from nepal_posts";
$queryExe = mysql_query($query, $connection);
while ($fetched = mysql_fetch_array($queryExe)) {
foreach ($fetched as $key => $value) {
echo $key."----->".$value." ";
}
}
and result was like this :
0----->9 id----->9 0----->10 id----->10
Why there is two times repetition ?
How should I code, to get proper result ?
my db table is like :
id -> 9, 10 title -> About Us / Om Oss, Our Services / VÃ¥r Verksamhet
post -> bla bla, bla bla

mysql_fetch_array
Returns an array of strings that corresponds to the fetched row, or
FALSE if there are no more rows. The type of returned array depends on
how result_type is defined. By using MYSQL_BOTH (default), you'll get
an array with both associative and number indices. Using MYSQL_ASSOC,
you only get associative indices (as mysql_fetch_assoc() works), using
MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
http://php.net/mysql_fetch_array

Use mysql_fetch_assoc() instead of mysql_fetch_array()
while ($fetched = mysql_fetch_assoc($queryExe)) {
foreach ($fetched as $key => $value) {
echo $key."----->".$value." ";
}
}

Related

Looping through resultings record and getting duplicates in foreach

So I am trying what I feel is a simply loop through a record result. My query returns one row of data. I am attempting to simply pull the value of each row from the returning record into a variable called $questions. However, my var $questions when printed out has duplicates in every space. It should read something like Bob|Ted|Joe|Sally and instead it is reading Bob|Bob|Ted|Ted|Joe|Joe|Sally|Sally. Why is the code below running twice in the foreach loop?
while ($row = mssql_fetch_array($result)){
foreach ($row as $col => $value) {
$questions.=$value."|";
}
}
echo "Questions: ".$questions."<br/>";
Here is all you need to do:
$questions = "";
while ($row = mssql_fetch_array($result)){
$questions .= $row['fieldName']."|";
}
echo "Questions: ".$questions."<br/>";
The foreach() in addition to the while() is unnecessary.
The mssql_fetch_array according to PHP doc:
In addition to storing the data in the numeric indices of the result
array, it also stores the data in associative indices, using the field
names as keys.
The result includes a normal array [0...n] with one element for each column, but also an associative array where each value is represented by a key named after the column name.
So if your first column is Id, you could get id from a row in two ways:
$id = $row[0];
# or you could do this
$id = $row['Id'];
This is why you get each value twice when looping through row.

PHP foreach row as $var, row name and row number duplicate [duplicate]

This question already has answers here:
php array from mysql
(2 answers)
Closed 8 years ago.
I coded a simple function to loop trough and display all variables in the sql table.
However foreach $row displays the rows two times, 1 time as a row name and 1 time as a row number.
1 : $row['NAME'] Name form
2 : $row[0]' Number form
PHP :
<?php
include "condetails.php";
$query = "select * from pagedetails";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
foreach($row as $var => $val) {
echo "VARNAAM :".$var;
echo "<br />";
echo "VALUE".$val;
echo "<br />";
echo "<br />";
}
}
?>
OUTPUT :
VARNAAM :0
VALUE1
VARNAAM :id
VALUE1
VARNAAM :1
VALUEdddd
VARNAAM :h1txt
VALUEdddd
It's displayed twice because mysql_fetch_array() grabs the column name and its number.
If you want just the column names try using mysql_fetch_assoc(), keep in mind mysql_* functions are depreciated and you should be using PDO / MySQLi :)
mysql_fetch_array returns a mixed array with keys as numbers and as column names. You probably want mysql_fetch_assoc(), which only returns the name keys.
From the manual:
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
What you you're really looking for is mysqli_fetch_assoc():
Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

mysql_fetch_array fetch date fetch each element twice

i hope to iterate the elements fetched from datebase
But the result looks very unexpected .
I found the code below print the $value and echo "<td id=".$key.$tag.">".$value."</td>";twice. Is there anything i misunderstood?
function selectTable($table){
$sql= "SELECT * FROM ".$table ;
$result=mysql_query($sql)
or die(mysql_error());
return $result;
}
$table = 'battery_con';
$result = selectTable($table);
unset($table);
while($row = mysql_fetch_array($result)){
......
foreach ($row as $key => $value) {
print $value;
echo "<td id=".$key.$tag.">".$value."</td>";
}
.....
}
You are using mysql_fetch_array which by default returns an array with two elements per column (this is what the second (optional) paramter means: result_type = MYSQL_BOTH).
One is indexed with an integer representing the column index, one is indexed with the column name.
That's why you get two entries in your list. You would set the second parameter to MYSQL_ASSOC to get just one value per column.
Please use mysql_fetch_assoc() place of mysql_fetch_array()
I hope it will help
In addition to #Andreas's answer by default mysql_fetch_array gives both associative and numeric indexes, if you don't want this you can limit it with the second parameter in your while loop:
$row = mysql_fetch_array($result, MYSQL_NUM); // numeric keys only
$row = mysql_fetch_array($result, MYSQL_ASSOC); // associative keys only
As previously mentioned by #sonusindhu you can also use mysql_fetch_row to only get numeric keys, or mysql_fetch_assoc to only get associative keys.
Update
The mysql_xxx() functions being deprecated you should consider using the mysqli_xxx() functions instead.
See the example 1 of the php manual for more details:
http://php.net/manual/en/mysqli-result.fetch-array.php

Wrong parameter count for max()

I'm trying to show the max value of column teams from mysql. Above the while loop I've selected teams from my mysql table and then as you can see in my code below I have included max($teams) - but it is returning an error? Where am I going wrong.
while ($rows = mysql_fetch_assoc($result)) {
$teams = $rows['teams'];
if($teams > "1") {
echo '<div class="bestbettor">'.'<span class="redtext">'."Bettor: ".'</span>'. $rows['username'].'</div>';
echo '<div class="bestbettor">'.'<span class="redtext">'." Bet: ".'</span>'.max($teams). " team accumulator".'</span>'.'</div>';
}
}
you must pass an array to max().
$teams = $rows['teams']; // saves as string.
if your teams were delimited by a comma then you could do something like:
$teams = explode(",",$rows['teams']); // saves as array
then you could do max()
If one parameter is given to max() it has to be an array of values of which max() will return the highest value in that array. It seems like you've just given it a single string.

two keys one value pdo query result

my code is this
$sql = "SELECT * FROM faculty";
foreach ($pdo->query($sql) as $row) {
foreach ($row as $key => $value) {
echo $key."-".$value."<br/>";
}
}
it's fairly simple what i'm doing. My question is why am i getting the same value
two times, one with a key the name of the row in mysql (e.g "surname") and one the position of the array.
Thank you for your time.
That's because your default fetch mode is set to
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0. Try e.g.
$pdo->query($sql, PDO::FETCH_ASSOC)
instead.
see also: http://docs.php.net/pdo.constants

Categories