How to only print one copy of the array? - php

The biggest problem is that I don't know what words to use. I think I'm looking for an argument or a flag...?
I'm getting an array back from a database fetch and the array stores each value twice, once with a word key and once with a number key..
[0] => Value1
[FirstEntry] => Value1
[1] => Value 2
[SecondEntry] => Value2
I'd like the array to only contain (fetch), or only print, either/or entry of Value1, but not both entries of Value1. How can I do this in PHP, preferably during the PDO fetch or during the print_r/echo loop? Thank you.

Looks like you are fetching data using a "both" fetch style, ie PDO::FETCH_BOTH, MYSQLI_BOTH, etc. These tend to be the default fetch styles.
If you just want a single style of index, use either a "num" or "assoc" style.
For example
$stmt = $pdo->prepare(...);
$stmt->execute();
$stmt->fetch(PDO::FETCH_ASSOC);

$stmt->fetch(PDO::FETCH_ASSOC);
Use This comments (PDO::FETCH_ASSOC) get unique Key Array From return From Data Base ..

Related

Is there another way to provide PDO with the unique column key when using PDO::FETCH_UNIQUE than in the SQL?

I am updating an old internal library to use PHP's PDO extension. In the old code, there's a function where the first parameter was a line of SQL and then the second parameter was an optional column to use as the key. I need to keep this same function signature so I don't break any code.
I'd like to use PDO's FETCH_UNIQUE fetch mode, but it would require me to parse every line of SQL that is passed in and add the key column to the beginning of the select. I'm worried that there are edge cases that I wouldn't think of that would break the call.
Is there another way in PDO to designate which column to use as the key when using PDO::FETCH_UNIQUE other than to add it directly to the column list in the SQL call?
Edit:
Here's some example code and more details:
$db = new Database();
$query = "first_name, last_name, contacts_id from contacts where first_name='George'";
$uniqueKeyField = "contacts_id";
$contact = $db->getRows($query, $uniqueKeyField);
Which would yield:
array (
[34] => array (
"first_name" => "George",
"last_name" => "Smith",
),
[452] => array (
"first_name" => "George",
"last_name" => "Johnson",
)
)
The problem is, I cannot always guarantee that the unique keyField will be first in the list like PDO requires because that was not a requirement of our API before.
After going through the manual, my guess is this is not possible to do with PDO::FETCH_UNIQUE and we will either have to use PDO::FETCH_ASSOC and loop through the results like we used to and build our own array or change every call to the above function in existing code to rearrange the fields so the unique keyfield is first. I was hoping someone knew of a way you could just pass the unique keyfield as an argument somewhere, but my guess is PDO faces the same problem we do - they have to have the keyfield in the query somewhere to pull out and put as the id in the returned array and they don't want to have to try to parse and add it to existing queries, thus the requirement to have it as the first field.

Correct Multidimensional array format to get output if exists

Ok, I'm probably going about this in the wrong way, so before I go any further, i thought I'd check with some experts.
Previously, after searching the DB I'd create an array with the array name of the date and there would only be 1 array per date. This could then be called and displayed on the appropriate part of the calendar.
But there will now potentially be multiple entries per date and I am trying to change to a multi-dimensional array.
$stmt = $dbc->prepare("SELECT stoname, date, hours1, hours2 FROM table WHERE MONTH(date)=? AND YEAR(date)=?");
$stmt->bind_param("ss", $month, $year);
$stmt->execute();
$stmt->bind_result($sto_name, $DB_date, $hours1, $hours2);
while ($stmt->fetch())
{
//Loop through to make new array corresponding to date in database
$foo="_".str_replace("-","",$DB_date); //take the "-" outta the date
${$foo}[$sto_name]=array(
'sto_name'=>$sto_name,
'hours1'=>$hours1,
'hours2'=>$hours2);
}
$stmt->close();
I'm not sure if this is the best way, although it does seem to work ok. However, it then makes it hard to access the arrays as the [$sto_name] is unknown and it appears I can't use numeric bits to call an associative array, e.g. $20160316[0]. In the output, I'd need to check if an array exists for that date irrespective of the [$sto_name], then can foreach through to print the array.
I had thought about something like:
${$foo}=array(
array(
'sto_name'=>$sto_name,
'hours1'=>$hours1,
'hours2'=>$hours2),
);
But then on the mysqli while loop it presumably overwrites the first array if there's a second array with the same date/$foo.
As you said that:-"But then on the mysqli while loop it presumably overwrites the first array if there's a second array with the same date/$foo"
So you need to change ${$foo}[$sto_name] to ${$foo}[$sto_name][].
Or
Better would be to use ${$foo}[] instead of ${$foo}[$sto_name]
Note:- It will works fine in both condition:- Either you got single data or multiple data.

Extra (double) array fields in return value when using PDO result database

I'm accessing a MySQL database from a PHP script using the PDO library, which I haven't used before (I am more familiar with MySQLi). I'm seeing extra, unexpected fields in the result. They aren't interfering with my code, but I'd like to know where they've come from.
Here is my database call:
SELECT
author.author_id AS author_id,
author.name_last AS name_last,
author.name_first AS name_first,
author.detail AS detail
FROM join_play_author
LEFT JOIN author
ON join_play_author.author_id = author.author_id
WHERE join_play_author.play_id = :play_id
ORDER BY author.name_last
I then bind and execute successfully, and my results contain all of the fields I've requested, with the appropriate labels. However, each field occurs twice in the result set: once with the label I requested, and once with an extra auto-incremented value. For example, one result set (printed using print_r()) looks like this:
Array
(
[author_id] => 41
[0] => 41
[name_last] => Dekker
[1] => Dekker
[name_first] => Thomas
[2] => Thomas
[detail] => 0
[3] => 0
)
These double fields aren't actively interfering with my code, but they are annoying during debug and I worry that they could affect performance for large result sets, which will be a concern on the production site.
Removing the AS tags doesn't affect the result array.
Any ideas? Is this just a feature of PDO--and if so, is there any way to turn it off? I don't ever remember seeing these extra fields in MySQLi results, although it's possible I missed them.
The PHP library is probably setting PDO::FETCH_BOTH as the result. If you don't want the extra keys set in your array you would need to change it to PDO::FETCH_ASSOC. Most libraries allow you to change this without modifying code though. You will have to read the documentation on that.
Documentation on the PDO statement fetch options.
http://www.php.net/manual/en/pdostatement.fetch.php
As stated by chapka in his comment - use setAttribute to clear the results from double results:
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

php array from mysql

I'm using PHP to get a value from MySQL. My table has this form:
COL1 = MAIL mail#mail.com
COL2 = NAME myname
and I'm getting from the database the row of the user.
$query = mysqli_query($conn, "select * from user where mail = 'telmo#mail.com'");
$row = mysqli_fetch_array($query);
print_r($row);
But my output is very strange, it gives my like a bidimensional array like this:
Array ( [0] => mail#mail.com [MAIL] => mail#mail.com [1] => myname [NAME] => myname )
I'm learning PHP and I'm wondering if is this supposed to be like this. Because I would want something more like:
MAIL => mail#mail.com
NAME => myname
Maybe I'm not getting this syntax very well, but this is why I'm looking for help.
Thanks in advance
Thank you in Advance
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.
Either specify MYSQLI_ASSOC after your query, or use mysqli_fetch_assoc. from the manual:
resulttype This optional parameter is a constant indicating what type
of array should be produced from the current row data. The possible
values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM,
or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave
identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave
identically to the mysqli_fetch_row() function. The final option
MYSQLI_BOTH will create a single array with the attributes of both.
Manual: http://us2.php.net/mysqli_fetch_array

PHP fetch MySQL array with an index

When fetching an array from MySQL the rows are typically returned with a key from 0 to the size of your recordset:
row[0][key][value]
Is it possible to have one of the fields from the select statement returned as the key in the array?
For example. Assuming my data set has StudentID, Name, City, etc.
How can I select into an array where I could refer to the StudentID as the index like this:
rows[StudentID][Name]
rows[StudentID][City]
etc.
Thanks!
PDOStatement::fetchAll
To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.
// Other PDO stuff to get a statement - abstract below
$result = PDOStatement::fetchAll( PDO::FETCH_COLUMN | PDO::FETCH_GROUP, 0 );
See example 3 on this page
Depending on which library you are using:
mysql_fetch_assoc()
mysqli_fetch_assoc()
PDO fetches both by default.

Categories