Re-usable PDO query function to multidimansional array - php

I'm trying to build a re-usable function to multidimansional array for every tablename i put in.
Like most i start mine tables whit ID and want to start the array whit that id, so not start whit 0 :) . foneticly--> $my_array[id]["email"]
So to build it i thought "what do i need" and found : $count_colum, $total_row an ofcource the data itself.
I know how to build a array, but i dont know how to build a "variable" array.
I also know i cant use PHP inside a array :) (whish would help iff you tell me)
$my_array = array( $row['id'] for ($i = 0; $i < $count_colum; $i++){...}
I also hope somebody knows what i mean :) I'm a little bit new to this all ;)
This is what i get this far:
function make_MDA($tablename)
{
$dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
$query = $dbh->prepare("SELECT * FROM `".$tablename."`");
$query->execute();
$count_colum = $query->columnCount();
$result = $query->fetchAll();
$total_row = count($result);
for ($i = 0; $i < $count_colum; $i++)
{
$meta = $query->getColumnMeta($i);
$column[] = $meta['name'];
}
foreach ($result as $row)
{
$my_array = array( $row['id'] //this is where I'm stuck
}
// echo $column[3];
// echo $total_row;
// echo $count_colum;
}

This should work, don't overcomplicate things:
function make_MDA($tablename)
{
$dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
$query = $dbh->prepare("SELECT * FROM `".$tablename."`");
$query->execute();
$result = $query->fetchAll();
foreach ($result as $row)
{
$id = $row['id'];
$my_array[$id] = $row;
}
return $my_array;
}
I would make the connection to the database $dbh once outside this function.

Related

How to display data from database MSSQL using foreach/for loop in SQLSRV PHP [duplicate]

This question already has answers here:
How to use foreach get data from the database table --
(3 answers)
Closed 3 years ago.
I'd like to display each rows in a specific column from my db_table. Found below is the code:
$get_sname = sqlsrv_query($conn, "SELECT [columnName] FROM [db_table] inner join [db_table2] on [col_fkey] = [col_pkey] WHERE userName = '$user'",array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
$rdr_sname = sqlsrv_fetch_array($get_sname, SQLSRV_FETCH_ASSOC);
$str = $rdr_sname['[columnName]'];
$rows = sqlsrv_num_rows($get_sname);
if($rows == false){
echo "\nerror\n";
}else{
$a = array($str);
for($i = 0;`$i < $rows;` $i++){
foreach($a as $b){
echo implode($a)."</br>";
}
}
This loop
$a = array($str);
for($i = 0;$i < $rows; $i++){
foreach($a as $b){
echo implode($a)."</br>";
}
}
returns the rows from my db in this format:
rowName
rowName
rowName
what I would like it to return is something like:
rowName1
rowName2
rowName3
I really appreciate all the help I can get on this. Thanks.
Explanations:
You need to make some corrections in your code:
Use parameterized statements to prevent SQL injections. Function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
The code in the question fetches only the first row in the result set, because sqlsrv_fecth_array() is executed only once. You need to execute sqlsrv_fetch_array() in a loop to fetch the data from all rows.
Example:
You may try with the following code:
<?php
// Statements
$sql = "
SELECT [columnName]
FROM [db_table]
inner join [db_table2] on [col_fkey] = [col_pkey]
WHERE userName = ?
";
$get_sname = sqlsrv_query($conn, $sql, array($user), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($get_sname === false){
echo print_r( sqlsrv_errors());
echo "<br>";
exit;
}
// Results
$rows = sqlsrv_num_rows($get_sname);
if ($rows === false) {
echo "Error"."<br>";
} else {
while ($rdr_sname = sqlsrv_fetch_array($get_sname, SQLSRV_FETCH_ASSOC)) {
echo $rdr_sname['columnName']."<br>";
}
}
// End
sqlsrv_free_stmt($get_sname);
?>
Use this code,
first declare the $count variable. like
$count = 0;
$a = array($str);
for($i = 0;$i < $rows; $i++){
foreach($a as $b){
echo implode($a).$count."</br>";
$count++;
}
}
In case somebody lands here looking for answers, here is the code that's fully working.
$get_store = sqlsrv_query($conn, "SELECT [columnName] FROM [db_table] inner join [db_table2] on [col_fKey] = [col_pKey] where userName = '{$user}'");
if($rows == false){
echo "\nerror\n";
}
else{
$sname = array();
while($storename = sqlsrv_fetch_array($get_store, SQLSRV_FETCH_ASSOC))
{
$sname[] = $storename;
}
foreach($sname as $storename){
echo $storename['storeName'];
}

get array values with a function in PHP

What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

PHP Array not being delivered

I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Categories