mysql_fetch_array fetch date fetch each element twice - php

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

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.

Read data from mysqli_fetch_array like a multidimensional array?

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.

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

How to print only index of an array

Using select query am select some data from database.
i fetched data using while loop.
while($row=mysql_fetch_array($query1))
{
}
now i want to print only index of $row.
i tried to print using following statements but it prints index and value(Key==>Value)
foreach ($row as $key => $value) {
echo $key ;
}
and i tried array_keys() also bt it is also not helpful to me.
echo implode(array_keys($row));
please help to get out this.
i need to print only index.
You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.
If you need just the numeric array, use:
while($row=mysql_fetch_array($query1, MYSQL_NUM))
By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.
You should pass separator(glue text) in Implode function.
For comma separated array keys, you can use below code.
echo implode(",",array_keys($row));
The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.
Store each $row in an array, like so:
$arr = array();
while($row=mysql_fetch_array($query1)) {
$arr[] = $row;
}
Now, to print the array keys, you can use a simple implode():
echo implode(', ', array_keys($arr));
$query1 from while($row=mysql_fetch_array($query1)) should be the result from
$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))
To get only the keys use mysql_fetch_row
$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
print_r(array_keys($row));
}

PHP, mySQLi: store the value of an array element into a variable

I have an SQL query which returns a single row as a result. This row contains only one column, an integer. I want to put this integer into a variable.
I execute my query and return the results of the query in an array as such:
$row = mysqli_fetch_all($result, MYSQLI_ASSOC);
I would like to save the value of the single column of this single row into a variable, for example $age. How can this be done?
(This query will always return one row with one column, always an integer)
mysqli_fetch_all doesn't return a row. But set of rows.
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$value = reset($rows[0]);
but it would be more logical to use a more suitable function:
$row = mysqli_fetch_row($result);
$value = $row[0]; // here you go.
Since you have only one column and your query returns only one row, that means you'll get only one value, and since you're fetching an associative array, you can do the following and store it in a variable.
$row = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($row as $r) {
$test = $r['age'];
}
However, since you're getting only one value out of that, you can just leave the result type out, and get $test = $r[0].

Categories