PHP echo duplicate rows when none exist - php

<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
$username ="matt";
$pass = "bs12kfj";
$db = "mytest";
$tbl = "test2";
mysql_connect(localhost,$username,$pass);
mysql_select_db($db) or die( "Unable to select database");
$res = mysql_query("SELECT * FROM test2;");
$num = mysql_numrows($res);
echo "<table border='2'><tr>The Peeps</tr>";
while ($r = mysql_fetch_array($res)) {
echo "<tr>";
foreach($r as $rs){
echo "<td>$rs</td>";
}
echo "</tr>";
}
?>
</body>
This code executes without error but the output contains a duplicate of every column of every row like so.
<table border='2'><tr>The Peeps</tr>
<tr><td>"matt"</td><td>"matt"</td><td>"phillips"</td><td>"phillips></td><td>"mathew.p#waburg.com"</td><td>"mathew.p#waburg.com"</td><td>20</td><td>20</td></tr><tr><td>"paul"</td><td>"paul"</td><td>"franklin"</td><td>"franklin"</td><td>"dude#live.com"</td><td>"dude#live.com"</td><td>30</td><td>30</td></tr><tr><td>"steve"</td><td>"steve"</td><td>"jobs"</td><td>"jobs"</td><td>"sjobs#apple.com"</td><td>"sjobs#apple.com"</td><td>23</td><td>23</td>
I don't understand why each column is duplicated when there is only a single <td></td> tag in the echo statement.
I also checked the db and the table does not contain duplicate entries.

This is what mysql_fetch_array does if you don't provide a second argument: gets you an associative array where the value is mapped to both the column name and the column index.
You can provide MYSQL_ASSOCas a second argument to have only the column name (or use mysql_fetch_assoc).

You are probably fetching your MySQL result array in the default mode of MYSQL_BOTH.
Try this:
while ($r = mysql_fetch_array($res,MYSQL_ASSOC)) {
echo "<tr>";
foreach($r as $rs){
echo "<td>$rs</td>";
}
echo "</tr>";
}
If you don't specify the second argument to mysql_fetch_array(), then MYSQL_BOTH is used, and you end up with both an associative array index of values, and a numeric array index, like this:
array(0 => 'field 1 val', 'field1_name'=> 'field 1 val',
1 => 'field 2 val', 'field2_name'=> 'field 2 val', etc);
Specifying either MYSQL_ASSOC or MYSQL_NUM will only retrieve either the associative values or the numerically indexed values respectively.

Change
while ($r = mysql_fetch_array($res)) {
to
while ($r = mysql_fetch_array($res, MYSQL_NUM)) {
or
while ($r = mysql_fetch_array($res, MYSQL_ASSOC)) {
The default value for the 2nd argument to mysql_fetch_array() is MYSQL_BOTH which gives you back an array indexed numerically and associatively. Alternatively, you could use mysql_fetch_row() (returns a numerically indexed array) or mysql_fetch_assoc() (returns an associative array) instead of mysql_fetch_array().

Easy.
If your SQL query is
SELECT foo FROM bar
then mysql_fetch_array returns 2 results. One with numeric index, one with the field name. Add a print_r($r) into your code to see the behaviour.
Solution? Use mysql_fetch_assoc

Related

php mysql remove numbered key's from fetched array row

I am trying to do a mysql fetch but it keeps adding numbered and labeled keys to the array. I want it to record only the labeled names and data in the array.
Am I using the wrong mysql call?
global $con,$mysqldb;
$sql="SHOW FIELDS FROM ".$dbtable;
$tr = mysqli_query($con,$sql);
$tl = mysqli_fetch_array($tr);
$tl = mysqli_fetch_array($tr);
$sql="SELECT * FROM ".$mysqldb.".".$dbtable." ORDER BY ".$tl['Field']." LIMIT 3";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$table[$row[1]] = $row;
}
foreach($table as $item => $data){
foreach(array_keys($data) as $pointer => $field) {
echo"pointer=".$pointer."\t";
echo"field=".$field."\n";
echo "data=".$data[$field]."\n";
}
}
reults
pointer=0 field=0 data=3823
pointer=1 field=PID data=3823
pointer=2 field=1 data=AA
pointer=3 field=symbol data=AA
pointer=4 field=2 data=1
pointer=5 field=value data=1
I want to omit 0, 2, & 4 from the array.
Take a look at the PHP.net manual for the mysqli_fetch_array() function.
You'll see there's an option called resulttype that will accept 1 of 3 values - MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH the default.
Using MYSQLI_ASSOC will remove the numbered keys.
Or check mysqli_fetch_assoc().
Thanks to thebluefox for a speedy response.
I replaced the fetch with:
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
And now the results are being recorded as they should.

Duplicate columns when displaying mysql data

I am generating a stylized table from mysql with php but for some reason it creates duplicate columns of my Date and Count. Can someone help figure out why this is happening to me? Thank you
<?php
include("dbconnect.php");
$link=Connection();
$result = mysql_query(
"SELECT Date, Count
FROM testLocation
WHERE Date
BETWEEN '2016-04-10 00:01:11' AND '2016-04-23 00:01:11'"
,$link
);
if($result!==FALSE){
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
echo '<tr><th>Date</th><th>Count</th></tr>';
while($row = mysql_fetch_array($result)) {
echo '<tr>';
foreach($row as $key=>$value1){
echo '<td>', $value1,'</td>';
}
echo '<tr>';
}
echo '</table><br />';
mysql_free_result($result);
mysql_close();
}
?>
First off all, please try to change your code to MySQLi, now for your problem you need to know that mysql_fetch_array will return an array with associative and numeric keys. From the docs:
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).
So to avoid duplicate data in your loop you need to use either of these three options:
// The important part here is to set the result type eg: MYSQL_ASSOC or MYSQL_NUM. By defualt it is MYSQL_BOTH and thats your problem right now.
$row = mysql_fetch_array($result, MYSQL_ASSOC | MYSQL_NUM);
// Or this, it will return rows with associative indexes (keys are named after the column), eg: $row['Date']
$row = mysql_fetch_assoc($result);
// Or this, it will return rows with numeric indexes, eg: $row[0]
$row = mysql_fetch_row($result);

mysql_fetch_array doesn't render the expect values of the SQL query

In the phpMyAdmin interface I run the following SQL query:
SELECT id FROM table WHERE family = '1' AND type = 'B1'
and receive the following results:
'1', '18546269', '51534064' which are correct.
Then I wrote the following code in PHP:
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
echo '(', implode(',',$array) ,')';
But receive the following result:
(1,1) which I didn't expected.
I thought that (1,18546269,51534064) would be displayed.
Then I wrote the following code to verify what should be displayed:
print_r ($array);
and was very surprised that the values were:
Array ( [0] => 1 [id] => 1 ).
In the end I wrote:
while($array = mysql_fetch_array($result)) {
echo $array['id'],',';
}
and as expected received exactly this:
1,18546269,51534064,
which I can't use because I need a string exactly like that: (1,18546269,51534064).
In fact I 'just' need a variable that gives me the same values of the SQL query that I run in phpMyAdmin.
I'm really confused and would be great if one of you guys could help me.
Solutions with mysqli would be appreciated as well. :-)
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysqli_query($link, $query);
$ids = '';
while($row = mysqli_fetch_array($result)) $ids .= $row['id'].',';
// Filter the text a bit
$ids = rtrim($string, ',');
$ids = '('.$ids.')';
echo $ids;
You basically initiate a variable, put all the ids in it, remove the last comma, append the brackets and that's it.
As documented under mysql_fetch_array():
Return Values
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.
[ deletia ]
Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
That is to say, the function returns only one row, by default as an array consisting of both associative and numeric-indexed columns from the resultset. You want instead make multiple calls to the function, with a suitable result_type parameter (as shown above).
mysql_fetch_array fetches array of row, not array of column. That means, if you would have ID and name, the fetched array would contain on each row an id and a name.
Quite a simple modification of your code that should fix the problem would be
$i=0;
$data=array();
while($array = mysql_fetch_array($result)) {
$data[$i]=$array['id'];
$i++;
}
echo '(', implode(',',$data) ,')';

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

How to count fields in row?

How can I count how many fields there are in this row:
$row['number']
while ($row = mysql_fetch_array($result))
{
echo '
<td class="alt">'.$row['number'].'</td>
$number = $row['number']
}
It could depend on how you're populating $row. If you use mysql_fetch_assoc() or mysql_fetch_row() you can just use count($row). However, if you use mysql_fetch_array() you'll need to divide by 2 since it returns both enumerated and associative values.
There are countless other methods of populating $row. It's all merely speculation without having more information.
Try to use mysql_num_fields().
Example:
<?php
$result = mysql_query("SELECT `field1`,`field2` FROM `table`");
/* returns 2 because field1, field2 === two fields */
echo mysql_num_fields($result);
?>

Categories