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);
Related
When I use mysqli_fetch_array() I get an array, but how do I read the values? Is a While-Loop the only option, or can I pick any value from a row and column like a multidimensional array with index like row[0] column [3] ?
while loop fetches you a row per iteration.
You can get all rows as multidimensional array with mysqli_fetch_all
After that you can use pick your values with [rowNum][colNum]
But beware when your result has lot of rows - array can be very big and cause memory or other issues.
Update to clarify:
if you want to receive multidimensional array of rows there are two ways:
First: iterate over mysqli_result with fetch_assoc/fetch_array and append row to array:
$rows = array();
while ($row = mysqli_fetch_array($res)) {
$rows[] = $row;
}
echo $rows[0]['whatever'];
Second: receive all results with one function call:
$rows = mysqli_fetch_all($res, MYSQLI_ASSOC);
echo $rows[0]['whatever'];
That's all. No more methods are available.
It depends how you are returning your results from the database.
there are flags in your mysqli_fetch_array function which you can set to modify your returned result.
If you use $row = mysqli_fetch_array($result, MYSQLI_ASSOC); or in OOP $row = $result->fetch_array(MYSQLI_ASSOC);
then you can access your returned result as column name in your while loop like $row['name'] or $row['age']
Or if you use $row = mysqli_fetch_array($result, MYSQLI_NUM); or in OOP $row = $result->fetch_array(MYSQLI_NUM);
then you can access your returned result in while loop like $row[0] or $row[3]
Simple example would be
while($row = mysqli_fetch_array($result)) {
echo $row['name'] . " " . $row['age'];
}
For further information. Read PHP.net Fetch Array
Your question suggests that your goal is just to get a single value. If that is the case, you should limit your query to only return what you're looking for rather than getting everything and then finding what you want in the results with PHP.
For the column, specify the one column you want instead of using *, (SELECT one_column FROM your_table) and for the row, either use a WHERE clause to select a specific id (provided that is defined on your table) or use a LIMIT clause to select a specific row number from the result set. Then you won't have to fetch in a loop or fetch all. Your query result (if it's successful) will just have one row with one column, and you can fetch once and get your value.
Granted, if you're going to need to do this repeatedly (i.e. in a loop), it isn't the best approach.
This post gives four ways of retrieving the result of a MySQL query:
mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both
$row = mysqli_fetch_array($result);
echo $row[0]; // or
echo $row['online'];
mysqli_fetch_assoc — Fetch a result row as an associative array
$row = mysqli_fetch_assoc($result);
echo $row['online'];
mysqli_fetch_object — Returns the current row of a result set as an object
$row = mysqli_fetch_object($result);
echo $row->online;
mysqli_fetch_row — Get a result row as an enumerated array
$row = mysqli_fetch_row($result);
echo $row[0];
Is there any significant difference between these four functions, in terms of either performance or functionality, or can they be used interchangeably?
Is there any significant difference between these four functions
No.
can they be used interchangeably?
Yes.
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 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);
?>
<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