I want to fetch values from a table in a MySQL database into PHP.
What kind of array will mysql_fetch_array($result) return? Associative or numeric?
array mysql_fetch_array ( resource $result [, int $result_type =
MYSQL_BOTH ] )
It depends on the second parameter which is default MYSQL_BOTH and could be MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
More info about mysql_fetch_array.
From the manual:
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
It returns an array with both numeric and string indexes.
Related
I have a script that is outputting to a CSV file. However, even though there is currently one row in the database, the output I'm getting is echoing out each column from each row in the table twice.
For example:
1,1,John,John,Smith,Smith,2014,2014
Should be
1,John,Smith,2014
This worked fine before I went with PDO and prepared statements, so I'm thinking maybe I'm not understanding how fetch() works correctly.
Below is my code. Any idea what I could be doing wrong?
// get rows
$query_get_rows = "SELECT * FROM Contacts ORDER BY date_added DESC";
$result_get_rows = $conn->prepare($query_get_rows);
$result_get_rows->execute();
$num_get_rows = $result_get_rows->rowCount();
while ($rows_get_rows = $result_get_rows->fetch())
{
$csv .= '"'.join('","', str_replace('"', '""', $rows_get_rows))."\"\n";
}
echo $csv;
exit;
You should say to PDO, that you want only an associative array or a numbered array:
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_ASSOC))
to get an associative array or
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_NUM))
to get an array indexed by the column number
from PDOStatement::fetch
fetch_style
Controls how the next row will be returned to the caller.
This value must be one of the PDO::FETCH_* constants, defaulting to
value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to
PDO::FETCH_BOTH).
PDO::FETCH_ASSOC: returns an array indexed by column name as returned
in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column
name and 0-indexed column number as returned in your result set
I have a script that is outputting to a CSV file. However, even though there is currently one row in the database, the output I'm getting is echoing out each column from each row in the table twice.
For example:
1,1,John,John,Smith,Smith,2014,2014
Should be
1,John,Smith,2014
This worked fine before I went with PDO and prepared statements, so I'm thinking maybe I'm not understanding how fetch() works correctly.
Below is my code. Any idea what I could be doing wrong?
// get rows
$query_get_rows = "SELECT * FROM Contacts ORDER BY date_added DESC";
$result_get_rows = $conn->prepare($query_get_rows);
$result_get_rows->execute();
$num_get_rows = $result_get_rows->rowCount();
while ($rows_get_rows = $result_get_rows->fetch())
{
$csv .= '"'.join('","', str_replace('"', '""', $rows_get_rows))."\"\n";
}
echo $csv;
exit;
You should say to PDO, that you want only an associative array or a numbered array:
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_ASSOC))
to get an associative array or
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_NUM))
to get an array indexed by the column number
from PDOStatement::fetch
fetch_style
Controls how the next row will be returned to the caller.
This value must be one of the PDO::FETCH_* constants, defaulting to
value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to
PDO::FETCH_BOTH).
PDO::FETCH_ASSOC: returns an array indexed by column name as returned
in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column
name and 0-indexed column number as returned in your result set
While working with PHP ,handling connection's with Database (MySQL)
$result = mysql_query('select * from products');
$row = mysql_fetch_array($result);
And yesterday founded out that array $row had Duplicate data within.
First you have Data's selected from database arranged in Indexes like : $row[0] = ID; than you also could find $row['ID'] = ID.
So is this only a feature of the Framework ,which copies data Virtually or are these Data's stored twice in array .
To get only one value set, you need to pass a second parameter to mysql_fetch_array.
either "MYSQL_ASSOC" to get an associative array, or "MYSQL_NUM" to get a normal array.
Example:
$row = mysql_fetch_array($result, 'MYSQL_ASSOC')
This will return:
$row['id']
Documentation
Straight from the manual:
mysql_fetch_array — Fetch a result row as an associative array, a
numeric array, or both
The prototype of the function says that
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
meaning that it returns both arrays by default - that is - duplicating the info
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. Please see: mysql_fetch_array.
Each row in $result has an index, a name and a value. You can look up a row's value by either index or name.
See the documentation for mysql_fetch_array()
Default setting is to fetch an array with both numeric and associative array. See PHP manual to change that.
Now we can access the values from mysql result set based on the index and/or with the name.
For eg: SELECT name,id FROM tbl_user
name = resultset[0] OR name = resultset['name']
I need to retrieve the values from mysql result set with only index or with name.
i am using PHP.
You can get result row as an associative array, a numeric array, or both.
mysql_fetch_array can be used. Use make of the second optional parameter to get the result in desired array type.
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
result type can be MYSQL_ASSOC, MYSQL_NUM or MYSQL_BOTH (default)
you can also use the mysql_fetch_assoc, if you need result only an associative array.
use
mysql_fetch_array($resultset);
or to get associative array use
mysql_fetch_assoc($resultset);
Check this link for details mysql fetch array
I was hoping someone could show how to properly append an array created with an sql query with data from a second query.
I have an array I created from a mysql resource which is correct.
while($row = mysql_fetch_array($result)){
$first_pass[] = $row;
}
But before I finish with the $first_pass array I want to do a second query, so inside the while loop before the $first_pass array I added;
$p = $row['productid'];
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = $p' AND fieldid ='11' ");
$goog = mysql_fetch_row($gle);
$row['google_cat'] = $goog[0];
my question is, no matter how I add this query to the existing array, when I dump it, it does not look like just another index added to the array. I have tried the mysql_fetch_row with my own created index and I have tried using mysql_fetch_array but then it shows as another array in the array.
I think it will function fine the way it is but it does not look proper.
This is what the dump looks like:
array0
=>array
0 => string '3614' (length=4)
'variantid' => string '3614' (length=4)
1 => string '1406' (length=4)
'productid' => string '1406' (length=4)
2 => string '180-GL-QT-CAY-M' (length=15)
'productcode' => string '180-GL-QT-CAY-M' (length=15)
google_cat => 'Clothing> Gloves'
where google_cat looks nothing like the rest of the array. So any input is appreciated.
Thanks
The difference is, your initial $row is populated using mysql_fetch_array() which defaults to using the MYSQL_BOTH fetch method.
This creates an array using both numeric indices and column name keys.
When you append your 'google_cat' key, you're only creating an associative index.
Unless you're actually going to use the numeric indices, I'd recommend sticking to mysql_fetch_assoc() instead of mysql_fetch_array()
Actually, what I really recommend is ditching the mysql extension all together and moving to PDO.
I think you have an error in your MySQL syntax. Try:
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = '". $p ."' AND fieldid = '11';");
You could also try replacing $row['google_cat'] = $goog[0]; with:
$row['google_cat'] = $goog[0][0];
...So it gives you the interior array of the first array in the multidimensional row return array. (Array array arraaayyyyyy...)
First use the same method to get your arrays from mysql (either mysql_fetch_array or mysql_fetch_row) not both.
then you can use
array_merge($row, $goog);
to concatenate the arrays together. beware the warning that if two elements have the same associative key the last one in the list will be the value of that key.
http://php.net/array_merge
Error in your syntax man!
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = $p' AND fieldid ='11' ");
Is missing an apostrophe...
Should be:
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = '$p' AND fieldid ='11' ");