How to fetch results in an array with ZF2 - php

I am trying to get some distinct values from DB with ZF2 using Tablegateway.
$select = $this->sql->select($tableGateway->getTable());
$select->columns(array('city'));
$select->quantifier('DISTINCT');
$stm = $this->sql->prepareStatementForSqlObject($select);
$res = $stm->execute();
return $res;
This is returning an Iterate object, and I would like to have all the cities in an array. How can I do this ?

// whatever $select
$stm = $this->sql->prepareStatementForSqlObject($select);
$res = $stm->execute();
$resultSet = new \Zend\Db\ResultSet\ResultSet;
$resultSet->initialize($res);
foreach ($resultSet->toArray() as $row) {
// ...
}

Related

Adding elements from an array to a sql query in PHP

I'm trying to put an array with values returned from a function to a sql query in PHP. Looking for information on how to do this, I tried to change the format of the array with the parameters fetch_assoc and fetch array, but it didn't help. I also tried to do a foreach loop for this array and execute sql with each iteration, but it also didn't do anything. How can I do this ?
This is my function which returns me an array of values:
public static function getLilanteProductCategoryForEmpik() {
$returnedArray = [];
$pdo = PDOConnector::getConnection();
echo $query = "SELECT product_type FROM `shopifyProductsLilante`
INNER JOIN offers_import_error_report_3839_14794292
WHERE shopifyProductsLilante.sku=offers_import_error_report_3839_14794292.sku";
$stmt = $pdo->prepare($query);
$stmt->execute( );
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$returnedArray[] = $row;
}
var_dump($returnedArray);
return $returnedArray;
}
and this is the function where I want to put the values from the array in the sql query:
public static function getEmpikCategoryToCSVFile() {
$returnedArray = [];
$lilanteProductCategory = MysqlProvider::getLilanteProductCategoryForEmpik();
$pdo = PDOConnector::getConnection();
foreach($lilanteProductCategory as $lilanteCategory)
{
echo $query = "SELECT empik_category FROM `empik_categories` INNER JOIN shopifyProductsLilante
WHERE $lilanteCategory=empik_categories.lilante_category";
}
$stmt = $pdo->prepare($query);
$stmt->execute( );
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$returnedArray[] = $row;
}
print_r($returnedArray);
return $returnedArray;
}

php array scope issue - returns last row from array

I am changing mysqli connections to prepared statements, I always come across this issue, when I am putting values in an array, I'm wondering if someone could explain why I do this incorrectly every time. When I print the returned array from the function it only shows me the last stored values in the array, as opposed to every row in the array.
function getResults($db) {
$statement = $db->prepare("SELECT inv_id, serial_num, equip_id, equip_title, equip_cat, input_date, date_modified FROM equip_inv");
$statement->execute();
$statement->store_result();
$num_of_rows = $statement->num_rows;
$statement->bind_result($invId, $serial, $equipId, $equipTitle, $equipCat, $inputDate, $dateMod);
while ($statement->fetch()) {
$resultArray = array();
$resultArray['inv_id'] = $invId;
$resultArray['serial_num'] = $serial;
$resultArray['equip_id'] = $equipId;
$resultArray['equip_title'] = $equipTitle;
$resultArray['equip_cat'] = $equipCat;
$resultArray['input_date'] = $inputDate;
$resultArray['date_modified'] = $dateMod;
}
return $resultArray;
}
You're reseting $resultArray in each loop. You can create a new array $results = array(); and push $resultArray to it in each loop. Try :
function getResults($db){
$statement = $db->prepare("SELECT inv_id, serial_num, equip_id, equip_title, equip_cat, input_date, date_modified FROM equip_inv");
$statement->execute();
$statement->store_result();
$num_of_rows = $statement->num_rows;
$statement->bind_result($invId, $serial, $equipId, $equipTitle, $equipCat, $inputDate, $dateMod);
$results = array();
while ($statement->fetch()){
$resultArray = array();
$resultArray['inv_id'] = $invId;
$resultArray['serial_num'] = $serial;
$resultArray['equip_id'] = $equipId;
$resultArray['equip_title'] = $equipTitle;
$resultArray['equip_cat'] = $equipCat;
$resultArray['input_date'] = $inputDate;
$resultArray['date_modified'] = $dateMod;
$results[] = $resultArray;
}
return $results;
}

PHP prepared statement not returning array

My array is empty when I'm binding an id variable. The table contains 5 columns that I'd like in an array. This is what I tried:
$records = array();
$id = 22;
if($results = $db->prepare("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param('i', $id);
$results->execute();
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
print_r($records);
you are binding param 'i' but using a '?' placeholder. Use one of these:
if($results = $db->query("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param(1, $id);
or
if($results = $db->query("SELECT * FROM categories WHERE id = :i")) {
$results->bind_param(':i', $id);
See http://www.php.net/manual/en/pdostatement.bindparam.php for more examples.

Return associative array from function

This is how I would normally run a loop with database information
$query = "SELECT * from courses ORDER BY id DESC LIMIT 4";
$stmt = $db->prepare($query);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { }
Now $row[] can be used to represent database information within the loop.
My problem is that I'll be utilizing this query a lot for separate while loops. However, I don't wish to have to complete this statement every time I require it, so I want a function to be able to refer to with any variables required.
For instance, I tried.
function retrieve_assoc_array_limit4($table) {
$user = '***';
$pass = '***';
$db = new PDO('mysql:host=localhost;dbname=***', $user, $pass);
$query = ("SELECT * FROM ? ORDER BY id DESC LIMIT 4");
$stmt = $db->prepare($query);
$stmt->bindValue(?, $table);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row;
}
But when trying to while it I get an unlimited amount of returns of the same information whiled.
while($row = retrieve_assoc_array_limit4($table_name)) {
exho $data;
}
My question is how logically to use the first code in a function so that I can use it in the same with without writing out the full statement relentlessly.
many ways of doing this, to use your code with little changes:
calling fetchAll() instead of fetch():
function retrieve_assoc_array_limit4($table) {
$user = '***';
$pass = '***';
$db = new PDO('mysql:host=localhost;dbname=***', $user, $pass);
$query = ("SELECT * FROM ? ORDER BY id DESC LIMIT 4");
$stmt = $db->prepare($query);
$stmt->bindValue(?, $table);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
then call your function and do a while or foreach:
$rows = retrieve_assoc_array_limit4($table_name);
foreach($rows as $row){
//do your stuff
}

JSON parse Mysql query result in php pdo

I am trying to do following
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return return json_encode(array('Result'=>$row);
Works and fetches all entries in a table make then JSON Array and send them,
However I want to make a query where selected ids must be send in a JSON Array
E.g 10, 20, 30
I assume that this will be done in a For loop perhaps
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_OBJ)))
Now suppose i have id's = 10,20,30 i want to append all of them in a JSON Array How can i do that?
just like return json_encode(array('Result'=>$row);
Edited Code
function GetMyMembers()
{
$myId = trim($_REQUEST['myId']);
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('SELECT valId FROM memList WHERE myId=:myId' );
$statement->bindParam(':myId', $myId, PDO::PARAM_INT);
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
// $row contains ALL THE ID'S
$placeholders = str_repeat('?,', count($row));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM players WHERE id IN ($placeholders)";
$statement = $conn->prepare($sql);
$statement->execute($row);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return $rows;
}
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[$row['id']] = $row;
}
return json_encode(array('Result'=>$data));
Btw, using raw API is not convenient. With Database abstraction library your code can be as short as 2 following lines:
$data = $db->getInd("id",'SELECT * FROM myTable');
return json_encode(array('Result'=>$data));
Edit:
if you have an array of ids, you need more complex code
$ids = array(1,2,3);
$data = array();
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
foreach ($ids as $id) {
$statement->bindValue(':id', $id, PDO::PARAM_STR);
$statement->execute();
$data[] = $statement->fetch(PDO::FETCH_OBJ);
}
return json_encode(array('Result'=>$data));
But while using Database abstraction library, there will be the same 2 lines:
$data = $db->getAll('SELECT * FROM myTable where id IN (?a)', $ids);
return json_encode(array('Result'=>$data));
Edit2:
if you need ids only
$statement = $conn->prepare('SELECT id FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row['id'];
}
return json_encode(array('Result'=>$data));
while using Database abstraction library, it's still 2 lines:
$ids = $db->getCol('SELECT id FROM myTable');
return json_encode(array('Result'=>$ids));
$ids = array(1,2,3);
$placeholders = str_repeat('?,', count($ids));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM table WHERE id IN ($placeholders)";
$sth = $dbh->prepare($sql);
$sth->execute($ids);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
echo json_encode(array('Result' => $rows));
Based on additional comments:
Best option:
$sql = '
SELECT *
FROM table1 AS t1
INNER JOIN table2 t2
ON t2.foreign_key = t1.id
';
or
$sql = 'SELECT id FROM table1';
$sth = $dbh->prepare($sth);
$sth->execute();
$ids = $sth->fetchColumn();
//next look above

Categories