pass an array to a function to query database in PP - php

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

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

Iterate array in Object from Class using fetch(PDO::FETCH_ASSOC)

I've a class with viewData() method that pull the data from the DB table.
I want to return the data result array in Class and iterate the array in Object
I'm able to make it work with fetchAll() but couldn't figure it out how to return the result with fetch() using while loop.
<?php
class CrudClass{
private $db;
function __construct($DB_con){
$this->db = $DB_con;
}
/* DATA VIEW METHOD */
public function viewData(){
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $row; // it doesn't work
}
// below code is working
/*if($stmt->rowCount()>0){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}*/
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
?>
The reason I want to do that way, because I don't want to pull the data at one go with fetchAll. Instead want to loop through each row at a time. Any help will be appreciated.
You should return array.
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
Now the whole method will look something like below
/* DATA VIEW METHOD */
public function viewData() {
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
}
This way you are assured that even if there is no result set, only array will get returned.
If above doesn't work. Try following two solutions.
1.Test explicitly for false.
while(($row = $stmt->fetch(PDO::FETCH_ASSOC) !== false) {
return $result[] = $row; // put each row in the result array
}
2.Use foreach
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
return $result[] = $row; // put each row in the result array
}
It is possible to return something you can use in a foreach without having to preload all the results (i.e. using PDOStatement::fetchAll()) and without returning the PDOStatement itself -- if that's what you are trying to do.
Because PDOStatement implements Traversable you you can construct an IteratorIterator from the PDOStatement and return that.
class CrudClass
{
public function viewData()
{
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return new \IteratorIterator($stmt);
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
Note that if you were try and foreach over $rows more than once, it will error because because the results of a PDOStatement cannot be rewound.

magento database sql not working

So do not have an idea why this function is not working? i am trying to select all the ids from the table but nothing is selected.
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows = ('value'=>$record, 'label'=>$record);
}
return $rows;
}
this function below works fine, I need the function above to do the same as teh function below.
public function toOptionArray()
{
return array(
array('value'=>1, 'label'=>'one'),
array('value'=>2, 'label'=>'Two'),
array('value'=>3, 'label'=>'Three'),
array('value'=>4, 'label'=>'Four')
);
}
There are a couple of issues with your code:
You're only selecting a single item (id, but later, I assume you're expecting an ID and a value).
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
record is an array from your SQL query, so you should be treating it as such. eg. $record['id']
$rows you want as an array, but you're overwriting it each time, so $rows[] = makes more sense
Something like:
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id, label FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows[] = array('value'=>$record['id'], 'label'=>$record['label']);
}
return $rows;
}
Try using the core read/write resource. Change
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
To
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');

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

How to fetch a table from MySQL in PHP

I'm a newbie to PHP and I'm just trying the very basics of MVC. Everything is going good but I have a problem while fetching data from MySQL and populating a HTML table with it.
The problem is that my code is just returning one row of the table (there are three rows in that table).
I have tried many things and right now I'm using arrays for storing the data and passing to controller and then to the view.
Query class file having a function for getting data and name queryDB:
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = "select * from tbl_cartypes";
$result = mysql_query($query) or die("Error: ".mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
return $data;
}
$connectObj->closeDB();
}
The controller class where the controller of this query is name carController.php:
public function getAllData(){
$runQuery = new queryDB();
$array = array();
$array = $runQuery->getTickets($userid);
return $array;
}
And the final view where I'm just echoing my data:
include "$path/controllers/carController.php";
$ticket = new carController();
$array = array();
$array = $ticket->getdata();
for($i=0;$i<count($array);$i++){
echo $array[$i]."<br />";
}
Output of this code is without error, but the problem is that it's just fetching one row of the table whereas there are three rows.
So any one can help me with this?
It's fetching all rows, but you're saving all the data to the same place ($data[0] through $data[5]), so all but the last row is getting overwritten.
This might work better:
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Using PDO and what other people have posted try using this
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = 'select * from tbl_cartypes';
$result = $connectObj->query($query);
$data = array()
foreach ($result as $row){
array_push($data, $row)
}
return $data;
}
$connectObj->closeDB();
}
Your problem is that you're overwriting the values of the previous table:
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
This will just re-write the last row of data over the key's in that table.
Try:
$data = array()
while($row = mysql_fetch_assoc($result)){
array_push($data, $row)
}
Your while loop is assigning just one row to array $data. in while loop instead try this
while($row = mysql_fetch_assoc($result)){
$data["car_id"][] = $row['car_id'];
$data["car_name"][] = $row['car_name'];
$data["car_model"][] = $row['car_model'];
$data["car_type"][] = $row['car_type'];
$data["car_price"][] = $row['car_price'];
}
return $data;
Now you can iterate through the array.

Categories