magento database sql not working - php

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');

Related

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

mySQL request not working

I'm not really much into PHP or mySQL so I hope you can help me.
I got a php script with a function that returns a json with all the entries in a database table:
public function select($table, $wheres = null)
{
$connect = $this->connect();
if ($wheres == null)
{
$query = mysqli_query($connect, 'SELECT * FROM `'.$table.'`');
} else {
$query = mysqli_query($connect, 'SELECT * FROM `'.$table.'` WHERE '.$this->wheres($wheres));
}
$i = 0;
$ret = array();
while ($row = mysqli_fetch_assoc($query)) {
foreach ($row as $key => $value) {
$ret[$i][$key] = $value;
}
$i++;
}
return ($ret);
}
Edit:
I have my application which calls this function. Everything worked as expected but then I added 2 more fields to one of the tables ( 1 text, 1 varchar ), and now when I call this function it returns nothing ; literally an empty string.
I've also noticed that if I just delete those new fields it works, which is kinda annoying plus I need those fields and I can't figure out where the problem root is.
Also, the application code is not the problem: when this function is called it only passes 2 parameters (the method name, and the table name), it can't be wrong.
By the way, here is the table structure if it may help you help me:
pic related
This function helps you to get data form database in json from , this return json
<?php
function getData($tbl_name=null,$id=null)
{
$con = mysqli_connect("localhost","root","","mydb"); //my db is my database name
if(!$con){ die( "could't connect with database" ); }
$sql = mysqli_query($con,'SELECT * FROM $tbl_name WHERE id = {"$id"}');
while($row = mysqli_fetch_assoc($sql))
{
#echo"<pre>";
#print_r($row); //this will return data form data base in array from
return json_encode($row);
}
}
?>

Output multiple rows in json in Zend Framework 1

I've searched and can't find an answer to my question.
I have the following code which is to loop through an array and then fetch back results for the different $id's.
The output when using echo json_encode($row); returns all results but the zend layout displays.
However when using $this->_helper->json($row,true); the layout doesn't display but only one result returns.
How can I return more than one result?
Any help would be much appreciated.
public function testAction()
{
//Get latest revision from database and loop through $id's
$id = array('308', '307', '306');
//Connect to database
foreach($id as $lId) {
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select('')
->from('LinktagRevisions')
->where('linktagId = ?', $lId)
->order('updated DESC')
->limit(1);
$stmt = $select->query();
while ($row = $stmt->fetch()) {
$this->_helper->json($row,true);
//Encode as json and echo result
// echo json_encode($row);
}
}
}
I think you can try this:
$result = array();
foreach($id as $lId) {
....
$stmt = $select->query();
$result[$lId] = $stmt->fetchAll();
}
$this->_helper->json($result,true);

Returning all rows, not just one

I am attempting to return all of the rows in a MySQL table. I have the following function:
function listTickets() {
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
while($row = mysqli_fetch_array($result)) {
return array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']);
}
mysqli_close($con);
}
However, print_r(listTickets()) does not return all rows, only the first row. How can I make it so that it will return every row? I know how to do it without using functions and whatnot, but I'd like to figure out how to do it with the function. Thanks!
When you use 'return', your function will return immediately - the first time round the loop. Subsequent runs through the loop are cancelled, as is the mysqli_close.
Also: (1) you are closing the database connection for everyone else (as a rule of thumb, if you open it, close it; if you don't open it, don't close it), and (2) $result isn't the finale result - consider using a more descriptive variable
So then it looks like this:
function listTickets()
{
global $con;
$query = mysqli_query($con, "SELECT * FROM tickets");
$result = array();
while($row = mysqli_fetch_array($query))
{
array_push($result,array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']));
}
return $result;
}
Next, I would add the option MYSQLI_NUM (or even MYSQLI_ASSOC) to mysqli_fetch_array, and remove the code which takes an array, and converts it into almost exactly the same array.
function listTickets()
{
global $con;
$query = mysqli_query($con, "SELECT * FROM tickets");
$result = array();
while($row = mysqli_fetch_array($query,MYSQLI_NUM))
{
array_push($result,$row);
}
return $result;
}
once you use return in a function, the function is ended and the value after return is returned.
Therefore, you need to store your database row somewhere and then at the end return all stored rows.
e.g.:
function listTickets()
{
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
$stack = array(); // <- the temp array
while($row = mysqli_fetch_array($result))
{
// push the db result to the stack
array_push($stack, $row);
}
mysqli_close($con);
return $stack;
}
Once a return statement is reached, the function is completed. You will need to gather the rows into some sort of collection and return the collection of rows.
Hope this helps
return exits the function immediately. Accumulate the output in the buffer then return it:
function listTickets()
{
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
buffer = array();
while($row = mysqli_fetch_array($result))
{
array_merge(buffer,array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']));
}
mysqli_close($con);
return buffer;
}

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