RedBeanPHP findAll only returns last item - php

I cannot get the findAll function to return more than the last row of the result query. I set R::debug( TRUE ) on the PHP script and it clearly says that there are 4 results in the returned data resultset. The query outputted works as expected, returning 4 rows, when I entered it directly into MySQL.
Here is my PHP code:
<?php
require 'include/rb.php';
include 'include/config.php';
R::debug( TRUE );
echo 'test4<br>';
$returnpeople = R::findAll('breadline');
echo '<br>';
foreach ($returnpeople as $key => $bean) {
echo $bean->tstamp.'<br>';
}
print_r($returnpeople );
?>
breadline is a MYSQL table with 2 fields:
tstamp and val
The system I have to deploy my code on runs PHP 5.3.3 and as such I've done the patch.
I've seen other people describe this issue as well, but they used parameters. I'm still getting it even after removing all parameters and calling R::findAll('breadline');.
I have not been able to reproduce this error, even when using parameters, on my test server which I have set to run PHP 5.3.3.

On Redbean website, there are some requirements :
Existing schemas
RedBeanPHP has been designed to build your database on-the-fly, as you go. Afterwards, you can manually change the schema to suit your needs (change column types, add additional indexes). Remember that the purpose of RedBeanPHP is to have an easy, configuration-less ORM. This can be achieved only by respecting certain conventions.
I assume your table must have a id field because in the method convertToBeans, the id is used :
public function convertToBeans( $type, $rows )
{
$collection = array();
$this->stash[$this->nesting] = array();
foreach ( $rows as $row ) {
$id = $row['id'];
$this->stash[$this->nesting][$id] = $row;
$collection[$id] = $this->load( $type, $id );
}
$this->stash[$this->nesting] = NULL;
return $collection;
}

Related

Having trouble converting mysql_result vars to mysqli

after searching a bit I've found posts in the same vein, but nothing thats specifically helpful to my problem.
I'm slogging through my code updating mysql to mysqli, and I'm hitting a snag on dumping search results into vars.
With a while loop I process each row and dump the fields into vars for display, then repeat until the resulting rows have all been displayed (basic search engine results)
My original code has the following var types (I'll show one for convenience)
$title = mysql_result($rs,$i,"title");
"rs" is the con and query, i is the row number, "title" is the field name
I see there are a few methods in the manual and mysqli_data_seek seems to be the correct route here, but I'm blowing it on parameters according to my editor (call uses 2 parameters and I'm using 3)
$title = mysqli_data_seek($rs,$i,"title");
I have 18 of these vars in the while loop, how can I make this work correctly? (procedural style)
There is no such method as mysql_result within the MySQLi-library. So you have to do it with one of the alternatives. Either run
$allData = mysqli_fetch_all($rs, MYSQLI_ASSOC); // Has to be run only once for the result!
// And access data via
$title = $allData[ $i /* row-number */ ]['title'];
// Or (you didn't provide your current loop)
foreach($allData as $i => $row) {
$title = $row['title'];
}
Or run
mysqli_data_seek($rs, $i); // Set pointer in mysqli to row-nr $i
$row = mysqli_fetch_assoc($rs);
$title = $row['title'];
Or run (most preferable solution I guess, but you didn't provide your current loop):
// Loop over all rows in the result-set
while($row = mysqli_fetch_assoc($rs)) {
$title = $row['title'];
}

Workaround for nested while->fetch

Good day everyone!
Currently I'm trying to find a workaround for my problem. As fair as I am concerned, MySqli doesnt support nested fetch'es, therefore my function doesn't quite work. I've tried to find a fix, but had no luck. My current code:
function viewQuestionnaire($id){
$questionStmt = $this->connection->prepare("SELECT id, type, name FROM TAP_questions WHERE questionnaire_id=?;");
$questionStmt->bind_param("i", $id);
$questionStmt->bind_result($id, $type, $name);
$questionStmt->execute();
$result = array();
while ($questionStmt->fetch()) {
$questions = new StdClass();
$questions->question_id = $id;
$questions->question_type = $type;
$questions->question_options = array();
$questions->question_name = $name;
if($questions->question_type=="2"){
$stmtOptions= $this->connection->prepare("SELECT id, options FROM TAP_options WHERE question_id=?;");
$stmtOptions->bind_param("i", $id);
$stmtOptions->bind_result($qu_id, $qu_opt);
$stmtOptions->execute();
while ($stmtOptions->fetch()) {
$options = new StdClass();
$options->option_id = $qu_id;
$options->option_name = $qu_opt;
array_push($questions->question_options, $options);
}
$stmtOptions->close();
}
array_push($result, $questions);
}
$questionStmt->close();
return $result;
}
As you can see, i'm trying to grab values from database, depending on the question type. If the question type is "2", i need to grab "additional" values from another table. How do i do that?
Vlad
I had more or less exactly this problem two weeks ago and found two working solutions:
1.) Nesting the queries, but using/initializing two different connections for them (even if it's to the same database)
2.) Doing one query first, saving the result in an array and using that array later inside the other query.
If you buffer the result, you can run the second query w/o loosing the result from the first query.
In Mysqli you buffer the result of an executed prepared statement (which by default is unbuffered) via the mysqli_stmt::store_result method.
...
$questionStmt = $connection->prepare(
"SELECT id, type, name FROM TAP_questions WHERE questionnaire_id=?;"
);
$questionStmt->bind_param("i", $id);
$questionStmt->bind_result($id, $type, $name);
$questionStmt->execute();
/* store result */
$questionStmt->store_result();
...
/* free result */
$questionStmt->free_result();
$questionStmt->close();
...

Migrating to MYSQLI : How to fitch result of query in while(list()) method instead of foreach() method?

I have very large PHP website, about 3000+ PHP files, all files are linked to main class named (lib.inc.php) which includes :
config.inc.php
users.inc.php
mysql.inc.php
I am doing quick migration from MYSQL to MYSQLI , and I am planning to do very minimal changes in MYSQL part, I did found many MYSQLI Classes which I can replace it with my old mysql.inc.php , but thats was not the big part of the job ... The big part is I have to change the code of the queries in almost each PHP file, I have around 3 to 5 MYSQL Queries which is currently in the following format structure :
$query = "
SELECT USER_ID,USER_NAME,USER_EMAIL,USER_LEVEL,USER_REG_DATE,USER_LAST_ACCESS,USER_LAST_IP
FROM USERS_TBL
LIMIT 0,20
";
$sth = $dbh -> do_query($query);
while (list($USER_ID,USER_NAME,USER_EMAIL,USER_LEVEL,USER_REG_DATE,USER_LAST_ACCESS,USER_LAST_IP) = $dbh -> fetch_array($sth)) {
// Do some thing with the result and print it
}
IN mysql.inc.php : I have the following Functions related to the above code :
function do_query($query) {
$this->sth = mysql_query($query,$this->dbh);
return $this->sth;
}
function fetch_array($sth) {
$this->row = mysql_fetch_array($sth);
return $this->row;
}
My question is :
How to migrate the above code from MYSQL to MYSQLI keeping in mind that I dont want to change the structure of loop part , as I want to all my while loops remain the same in all 3000+ PHP files , specially this part :
while (list($USER_ID,$USER_NAME,$USER_EMAIL,$USER_LEVEL,$USER_REG_DATE,$USER_LAST_ACCESS,USER_LAST_IP) = $dbh -> fetch_array($sth)) {
// Do some thing with the result and print it
}
In the current MYSQLI classes which I found in the net , all statements witch dealing with fetching array it has the following structure:
/**
* Retrieve results of a standard query
*/
$query = "SELECT USER_ID,USER_NAME,USER_EMAIL,USER_LEVEL,USER_REG_DATE,USER_LAST_ACCESS,USER_LAST_IP
FROM USERS_TBL
LIMIT 0,20";
$results = $database->get_results( $query );
foreach( $results as $row )
{
$USER_ID = $row['USER_ID'];
$USER_NAME = $row['USER_NAME'];
$USER_EMAIL = $row['USER_EMAIL'];
$USER_LEVEL = $row['USER_LEVEL'];
$USER_REG_DATE = $row['USER_REG_DATE'];
$USER_LAST_ACCESS = $row['USER_LAST_ACCESS'];
$USER_LAST_IP = $row['USER_LAST_IP'];
}
Notice that in mysqli version I have to assign each variable to another one so I can use them in different places in the code, but in my old code , I just need to type the variable inside the while (list(....)) methods .. instead of making each variables in separate line....changing the while(list()) methods to foreach() method will cost me hundreds of hours to apply this changes in my whole codes of 3000+ PHP files 600,000 lines of code .
So , How to apply current methods code in mysqli version ???
if I can get example of fetching result in while(list()) way using MYSQLI ,I will be much appreciated.

Codeigniter Database Record retrival - Best Practise - Performance

I'm checking an PHP project which is build using PHP Codeigniter. I'm new to PHP, I like to get your valuable feedback
To retrieve name and item number in php library/controller, call is made to Item Model as below
'name'=>$this->CI->Item->get_info($item_id)->name
'item_number'=>$this->CI->Item->get_info($item_id)->item_number
I suspect above two line of code will make two independent database sql call instead of one call to retrive the two column of same table. Ie., there will be performance degrade. But somebody can please let me know whether it fires two sql statements please?
I think we need to handle like object
$row = $this->CI->Item->get_info($item_id);
echo $row->name;
echo $row->item_number;
Please suggest. Thanks in advance.
Model Function:
function get_info($item_id)
{
$this->db->from('items');
$this->db->where('item_id',$item_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$item_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}

Zend Fetch on large table 10,000 + rows, ~100 columns

I have an sql view which returns over 10,000 records with about 120 columns (ridiculous, I know).
The view data is gathered from the database in PHP using a Zend_Db_Table_Abstract object. We have a report controller which does a fetchAll (which obviously creates a massive array) and stores the array in a view object. Next we have a view script which iterates over the array and echoes a json formatted array.
This is slowwww. Like over 1 minute to render this report, what can I do to speed this up?
Bare in mind I am very new to this project and have no knowledge of Zend and little of PHP. Also I can't give away to much due to data protection etc.
If you could ask what you need to help you gather the picture that would be great. But basically this is what the script does:
Report controller:
Setup some basic json report data (for data tables)
$this->view->report_data = fetchALL($oSelect);
View script:
Output the basic json stuff, then:
"report_data": [
<?php
for($i = 0; $i < count($this->report_data); $i++){
echo "[";
foreach($this->columns as $k=>$col){
echo '"'. $this->escape($this->report_data[$i][$col]) .'"';
if($k < count($this->columns) -1 ){
echo ',';
}
}
echo "]";
if($i < count($this->report_data) -1){
echo ",";
}
echo"\n";
}
?> ]
So after doing some research I gathered that I could use fetch() instead of fetchAll() so to get 1 row at a time, to avoid the massive array. However I tried to use the fetch() and got this error:
Call to undefined method Zend_Db_Table_Abstract::fetch()
So now I'm bummed.
My idea was to get each row and output each row Json formatted, however I don't really know how I would do this in the report controller/ view scenario. Would I have to just get rid of the view script and just use the controller to output the data?
Anyway why does fetch() not work, I can't actually see it in the docs either, well there is some array function _fetch()
Any help would be appreciated, any if you need more info just ask.
Thanks
See the docs for fetch().
The following is not very elegant, but could help you:
Model:
...
function getResults()
{
return $db->query('SELECT * FROM bugs');
}
...
Controller:
...
$this->view->report_data = $model->getResults();
...
View:
...
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
echo Zend_Json::encode($row);
}
...
I haven't tested the code, but you should get the idea.
You have to improvise use of framework here to gain that extra bit of performance
In controller
$this->view->result = mysql_query($sql);
In view
while ($row = mysql_fetch_assoc($this->result)) {
echo json_encode($row);
}
Note to setup mysql procedure interface read
http://php.net/manual/en/function.mysql-fetch-assoc.php
As you have realised from the error message Zend_Db_Table_Abstract does not have a fetch() method. It does, however, have a fetchRow() method that has this signature:-
/**
* Fetches one row in an object of type Zend_Db_Table_Row_Abstract,
* or returns null if no row matches the specified criteria.
*
* #param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
* #param string|array $order OPTIONAL An SQL ORDER clause.
* #param int $offset OPTIONAL An SQL OFFSET value.
* #return Zend_Db_Table_Row_Abstract|null The row results per the
* Zend_Db_Adapter fetch mode, or null if no row found.
*/
public function fetchRow($where = null, $order = null, $offset = null)
So replacing fetch() with fetchRow() and looping while !null === fetchRow() should work for you.
It is always worth delving into the code of Zend Framework to see what is on offer.
Zend Paginator may also be an option for you as it just fetches the records required to render the page.

Categories