I was reading the page https://www.codeigniter.com/user_guide/database/results.html
and I read if $row = $query->first_row() this gives object
and if we want this as array then we have to use
$row = $query->first_row('array') and this is ok.
But, can we replace these functions?
$row = $query->row(); //for object
and
$row = $query->row_array(); //for array
to a single function with different parameter.
Also if these functions have parameters like index,class then we can use the above functions like
$row = $query->row(array('index'=>5,'type'=>'array','class'=>'Users'));
//for array mentioned type here
$row = $query->row(array('index'=>5,'type'=>'object','class'=>'Users'));
//for object mentioned type here
Need some Guidance.
Thanks.
to a single function with different parameter. i think you are asking for a core system file modification here.. which is not good at all...why??? because what if you need to update your codeigniter version later on...you need to update your core files for that which in turn will replace your modified code....
anyways..the only difference between these two function (row and row_array) is.. row returns the datas as object whereas row_array() returns in array.....
what row() does is it gets single result in object...
This function returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object.
example
$query=$this->db->query('select * from table where id= "1"');
$row=$query->row() //these returns i object
$row=$query->row_array() //this returns in array..
however you can pass two optional parameters to row() function.. one being the row number of specific rows return... if not mentioned it returns the first row.. and second which is , name of a class to instantiate the row with.. you can go through the guide..for more information
Related
I very like the syntax :
$result = $db_connect->query("SELECT * FROM table")->fetch_assoc();
instead of more verbose
$query = $db_connect->query("SELECT * FROM table");
$result = $query->fetch_assoc();
$query->free();
My question is how do I free results from memory in case 1 ?
In other words : Do assigning a new value to the variable does automatically free the results ?
I've searched for that on stackExchange / Google with no success...and I found it's an interesting question.
Method Chaining (your first example) works by executing each following function on the object returned by the previous function. So you can do $db_connect->query("SELECT * FROM table")->fetch_assoc(); because query() returns a mysqli_result object and that object supports the fetch_assoc() method.
fetch_assoc(), in turn, returns...
... an associative array of strings representing the fetched row
in the result set, where each key in the array represents the name of
one of the result set's columns or NULL if there are no more rows in
resultset.
Since this result is an array (or NULL) and not an object, no further methods can be added to the chain after it.
Hello I would like to know is it possible to get column value as string. Instead of array in array:
Current query: Number::limit('1000')->get(['number'])->toArray()
The result at the moment is this:
Preferable result:
Before your toArray() call, add pluck('number'):
$result = Number::limit('1000')->get(['number'])->pluck('number')->toArray();
That's it! This will pluck just the number attributes from your result collection, and give you a single-level array.
The reason this works, is because you are getting a Collection back from get():
All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.
And the pluck method:
https://laravel.com/docs/5.1/collections#method-pluck
Update
Another, even more succinct method provided by #wunch in the comments:
$result = Number::limit('1000')->lists('number')->toArray();
I have this function in a linked file:
function getNumberOfHerps() {
$sql = "SELECT COUNT(ID)
FROM HERPES;";
return DBIface::connect()->query($sql);
}
I can call on this function from any other page in the website. What I want to do is to be able to use the result of the COUNT function in my php code on various pages, because I need to know how many herps there are in the database on several occasions in the code.
I tried this:
$result = getNumberOfHerps();
$numberOfHerps = $result['COUNT'];
But it caused a parse error on the second line, saying this:
Cannot use object of type PDOStatement as array.
Please tell me how I can use the result of a Count function in php code. Thanks :D
You are actually facing 2 separate items here that need your attention:
You can't access the COUNT(ID) returned from your query and
You are attempting to access data of a PDOStatement object as an array
So:
You can create an ALIAS for the value returned from the COUNT() function:
$sql = "SELECT COUNT(ID) as COUNT...";
This will provide to your result set a new column named COUNT that you can access your row count from.
Secondly, you need to perform a fetch operation on the PDOStatement in order to access it's data (this is what is causing your parse error). You have several options for accessing the result set in a PDOStatement:
list ($idCount) = $result->fetch();
// $idCount will now have the value of your COUNT column
or
$results = $result->fetch(PDO::FETCH_ASSOC);
// you can then access your COUNT as $results['COUNT'];
or even
$results = $result->fetch(PDO::FETCH_OBJ);
// you can then access your count as $results->COUNT
There are actually several additional FETCH_* styles available to use. The ones I've described though would likely be the most common. You can find more information about fetching PDO result sets at
http://us1.php.net/manual/en/pdostatement.fetch.php
I worked it out for myself, so I'll put my answer up for anyone else who finds this question:
I changed the function to this:
function getNumberOfHerps() {
$sql = "SELECT COUNT(1)
FROM HERPES";
return DBIface::connect()->query($sql)->fetchColumn(0);
}
So what the function now returns is the actual count value (the first column of the query). That means that in the webpage php file, you can access it in this way:
$numberOfHerps = getNumberOfHerps();
Much more simple.
I am trying to retrieve a specific field from the first row of my query results. The following works just fine...
$result = $db->query($query);
$firstrow = $result->fetch();
$desired_field = $firstrow["field"];
My question is, can i do this in one step without storing the first row of results in a variable? Thanks in advance!
You can use fetchColumn() to return a single column from the next row in the result set. If there is only one column in the result set, do:
$desired_field = $result->fetchColumn();
If there are multiple columns in the result set, specific the numeric index of the one you want:
$desired_field = $result->fetchColumn(1);
Take notice of the warning provided in the fetchColumn() documentation:
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.
You can use something like $firstrow = $db->query($query)->fetch() but this is not good practice to do with functions that aren't guaranteed to return an object.
The query() function can return FALSE on error, and the dynamic call to fetch() would be a fatal error. You can't call ->fetch() on a scalar FALSE value.
For example, try the following and your script will explode:
$firstrow = $db->query("SELECT * FROM table_that_does_not_exist")->fetch();
PDO does support a mode to throw exceptions instead of returning FALSE, so in that case you are guaranteed either query()->fetch() works, or else query() will throw an exception, so you will never reach the fatal error. But you might not be using PDO's exception mode.
The answer from #GeorgeCummins points out that there's a fetchColumn() method that you can use once you have a PDOStatement object, that's a good way to get a single column. If you only need one column, name that column as the only column in your select-list, and then always use fetchColumn(0):
$oneValue = $db->query("SELECT oneColumn FROM table")->fetchColumn(0);
Otherwise if you use fetch(), this returns an array. PHP 5.4 supports array dereferencing:
$oneValue = $db->query("SELECT oneColumn FROM table")->fetch()[0];
But if you're using PHP 5.3 or earlier this is not supported. And I've never tried it with the array returned by PDOStatement so if it's actually returning an ArrayObject or something this might not work anyway.
This is guarantee to work if and only if your query is correct and there is at least one row data.
$db->query($query)->fetch(PDO::FETCH_OBJ)->field;
example:
$query = $mydb->query('PRAGMA table_info("mytable")');
//variable query has now type of PDOStatement Object
print_r($query->fetchAll(PDO::FETCH_COLUMN,1)); // this result is ok
print_r($query->fetchAll(PDO::FETCH_COLUMN,2)); // but this result gives empty array
so is there any way to reuse statement object ?
A PDOStatement Object returns false when there are no more rows available. The call to fetchAll covers all rows which would then always return false on any following attempt to fetch. This limits the reuse of the statement object. You can use the PDOStatement::bindColumn to achieve what it looks as if you are attempting in your example.
$query = $mydb->query('PRAGMA table_info("mytable")');
// Variables passed to be bound are passed by reference.
// Columns are based on a *1* index or can be referenced by name.
$query->bindColumn(1, $bound_column1);
$query->bindColumn(2, $bound_column2);
$query->fetchAll();
print_r($bound_column1);
print_r($bound_column2);
Sure, you can re-use the statement object.
But think about this for a moment: If you already have fetched all PHP Manual, why do you expect that the second fetch all statement can still return something?
print_r($query->fetchAll(PDO::FETCH_COLUMN,1)); // this result is ok
print_r($query->fetchAll(PDO::FETCH_COLUMN,2)); // but this result gives empty array
PDO has a cursor that advances. Once at the end, there is nothing you can do but close the cursor PHP Manual and execute again.
You can re-use the statement object for that.
But I don't think you want/need to actually do that for your code. Instead, fetch all columns and then access them in the returned data by their index:
print_r($query->fetchAll(PDO::FETCH_NUM)); // this result is ok
You will see in the output that you now have 0-indexed column numbers per each row, so you can access the columns within the return data by their column-index - row per row.
$array = $query->fetchAll( args );
Then use the $array how you want.