PHP class array question - php

For some reason my array I am returning is not what I expect. Could someone explain to me why I am getting the current results, and what I can do to fix it? Here is the code in question:
public static function getProduct($_row, $_value)
{
$stmt = _DB::init()->prepare("SELECT pid, name, quantity, price, cost
FROM products
WHERE $_row = ?"
);
if($stmt->execute(array($_value)))
{
while ($row = $stmt->fetch())
return $row;
}
}
$product = Class::getProduct('pid',1);
print_r($product);
When I print the following array I am getting two results per row like so:
Array ( [pid] => 1 [0] => 1 [name] => Boondoggle [1] => Boondoggle [quantity] => 12 [2] => 12 [price] => 9.9900 [3] => 9.9900 [cost] => 12.9900 [4] => 12.9900 ) Boondoggle
I was only wanting to show the associative results. What is wrong with my function?

From the looks of it you are using PDO to communicate with your DBMS. The PDOStatement::fetch() method's first argument is a parameter to tell it what to return. By default it returns each column in both name format and numbered index format to allow iterating through columns easier. To just get the column names as indexes, you can pass it PDO::FETCH_ASSOC to your call. So the fetch statement would look like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)
See here for more details:
http://www.php.net/manual/en/pdostatement.fetch.php

Pass PDO::FETCH_ASSOC to your fetch call:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
edit: I'm just assuming you're using PDO, of course

Related

Loop not working with assosiative array Php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

PHP PDO SQL only returning one row of data instead of all rows

I am using PHP PDO extension to create a list of all items from a DB category table.
The expected results are not correct, only one row of data returned instead of all
rows which is expected.
By running the same SQL statement within the phpMyAdmin console I get the expected
results for all rows of data.
I need to know what I am overlooking with pdo.
Current code:
$catId = 0;
$sql = "SELECT *
FROM category
WHERE cat_parent_id = :catId
ORDER BY cat_name";
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindParam(":catId", $catId, PDO::PARAM_INT);
$_stmt->execute();
$rows = $_stmt->fetch(PDO::FETCH_ASSOC);
// display PDO result - only getting one row instead of all rows.
print_r($rows);
Array ( [cat_id] => 3
[cat_parent_id] => 0
[cat_name] => Shop
[cat_description] => Seminars
[cat_image] => c72e.gif
)
// NOTE: By running the same SQL within the phpMyAdmin
// console I get the expected results with all rows.
Array ( [cat_id] => 3
[cat_parent_id] => 0
[cat_name] => Shop
[cat_description] => Seminars
[cat_image] => c72e.gif
),
( [cat_id] => 1
[cat_parent_id] => 0
[cat_name] => Site Map
[cat_description] => List content links
[cat_image] => c83b.gif
)
PDOStatement::fetch() will only return 1 row at a time.
You could use PDOStatement::fetchAll():
$rows = $_stmt->fetchAll(PDO::FETCH_ASSOC);
or create a loop where you keep calling PDOStatement::fetch() until it returns false:
$rows = array();
while( $row = $_stmt->fetch(PDO::FETCH_ASSOC) ) {
$rows[] = $row;
}
But the latter example is a bit redundant, if you want to get all rows at once anyway, unless there are some memory concerns you want to address.
You have to use fetchAll like below:
$rows = $_stmt->fetchAll();
print_r($rows);

Mysql PDO return double result on select [duplicate]

I'm new to using $pdo statements so might be something simple I haven't yet read on php.net. I'm receiving duplicate results when querying the database.
Result:
[0] => Array
(
[umeta_id] => 31
[0] => 31
[user_id] => 2
[1] => 2
[meta_key] => fbmeta
[2] => fbmeta
[meta_value] => someMetaValueStuff;
[3] => someMetaValueStuff;
)
The query is quite simple:
function getData(){
global $pdo;
$query = $pdo->prepare('SELECT * FROM usermeta WHERE meta_key = "fbmeta" LIMIT 0,30');
$query->execute();
return $query->fetchAll();
}
print_r( getData() );
The problem is that the named keys (umeta_id, user_id, meta_key, meta_value) DO exist, the numeric keys do not. How come the query returns these? And how do I prevent them from even being returned?
It's not duplicates, it's just the current FETCH_MODE you're using. To get as associative keys only you need to specify as such; by default it fetches as both.
Use like so:
$query->fetchAll(PDO::FETCH_NUM); // to fetch with numeric indexes
$query->fetchAll(PDO::FETCH_ASSOC); // to fetch with associative indexes
fetchAll docs
fetch docs
This is not duplicate data fetchAll returns data in numeric array as well as associative array.
See the Docs
Use this for retrieving only associative array
return $query->fetchAll(PDO::FETCH_ASSOC);
seems to do the trick for me. Put this on top
use Illuminate\Database\Events\StatementPrepared;
when ever fetching include pdo::fetch_assoc
return($pdo->fetchAll(\PDO::FETCH_ASSOC));

PHP multi-dimensional array value as index

aside from doing the actual work of iterating through an associative array, pushing a value into a new array and setting that equal the array of remaining fields, is there an array function built into PHP that would do something like this?
if so, what is it?
i would be changing the following:
Array
(
[0] => Array
(
[0] => TEST //Name (Database column name
[1] => 12430 //ID (Database column name
[2] => Y //Save (Database column name
[3] => 100 //Wert (Database column name
)
into something like this:
Array
(
[12430] => Array
(
[Name] => TEST
[Save] => Y
[Wert] => 100
)
i work with while-loop:
....
while( $row = mysql_fetch_assoc($ergebnis) ) {
....
}
I think that you are going to have to iterate through the array. There may be a function here that could shorten the code by about a line, but I doubt it will make a noticeable difference to the readability and efficiency of your code.
So I would iterate through the array if I were your, quite short and simple.
$new_array = array();
while( $row = mysql_fetch_assoc($ergebnis) ) {
$new_array[$row[1]] = $row;
unset($new_array[$row[1]]);
}
Note that the mysql_ functions have been deprecated in PHP and you should be using mysqli_ or PDO instead, as it is more stable and secure.
Also, as #CBroe said, the mysql_fetch_assoc function will return the second part of your desired result already. The equivalent in PDO would be $query->fetch(PDO::FETCH_ASSOC);
Good luck!
Alter your query and add GROUP BY ID at the end.

PHP - Removing one array layer

I have a simple PHP function that will grab information from a database based on a unique ID:
function oracleGetGata($query, $id="id") {
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
return $results;
}
So for example $array = oracleGetData('select * from table') would return:
[1] => Array
(
[Title] => Title 1
[Description] => Description 1
)
[2] => Array
(
[Title] => Title 2
[Description] => Description 2
)
This is fine, however, if I just want to return one record $array = oracleGetData('select * from table where id = 1') it returns the data like:
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
Not only am I unsure of how to reference this (there is nothing identifying the array) I'd also like to somehow change my function so if it just returns one record, it will just be a simple one dimensional array.
I've looked into the usual PHP array functions but can't find anything that'll help, nor an easy way of identifying how deep the array is.
Would really appreciate any help, thank you
Use array_pop():
$array = array_pop(oracleGetData('select * from table where id = 1'));
You will then get one single array:
Array
(
[Title] => Title 1
[Description] => Description 1
)
Instead of an array embedded in another one:
Array
(
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
}
I think there is an logic error in your script:
Change
$results[ $row[$id] ] = $row;
into
$results[] = $row;
The problem is, that you want to have the Database key value as array key value, but you don't know the Database key, since you don't know what the query will look like.
You could try:
$results[$row['id']] = $row;
But this only works when all of your results have a Database key named "id".
You pass a $id in the function signature, but in the loop you uses $row[$id], Why? Maybe the error is there.
If you want a sequencial id in your result set, you don't need use the $id, you can uses array_push() function
array_push($result, $row);
OR
$results[] = $row;

Categories