Adding elements from an array to a sql query in PHP - 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;
}

Related

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;
}

pass an array to a function to query database in PP

I would like to pass an array with varying number of column names and the table to query database.
public function get_list() {
$list = func_get_args();
$table = array_pop($list);
$fields = implode(', ', $list);
$sql = "SELECT $fields FROM $table";
$data = array();
try {
$dbi = db::getInstance();
$stmt = $dbi->data->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[]=$row[$fields];
}
return $data;
}
catch(PDOException $ex) {
die($ex);
}
}
The query gets the table and the right column, if there is only one.
But, if the array includes more than one column, it says:
Undefined index: value1, value2
Is there a valid way to use a comma separated string to query more than one column?
Thanks a lot!
Not sure what you're trying to do with the $fields in the loop. Your query will only return the fields that you specified. So your code would be:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
But here are two ways to get the data as you are showing. Just assign in the loop:
while ($data[] = $stmt->fetch(PDO::FETCH_ASSOC)) {}
Or use a function to get all the rows:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
However, if I was going to take this approach I would pass in the table and fields (as an array) as specified arguments:
public function get_list($table, $fields)
To use the results outside of the function with dynamic fields, you would need to loop $rows to get them:
foreach ($this->model->get_list($fields, $table) as $row) {
foreach ($row as $field => $value) {
echo "$field contains $value";
}
}

How to fetch results in an array with ZF2

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) {
// ...
}

How to get multiple rows from mysql & PHP with this function

I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}

Insert sql query result to a new query

So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1

Categories