Difference between PDO::FETCH_* and the casting - php

I want to know the real difference in PHP PDO between the cast variable and the constant PDO::FETCH_* for the return query
Example:
$row = $stmt->fetch(PDO::FETCH_OBJ);
OR
$row = (object) $stmt->fetch();

There is no significant difference, but obviously the first line does less work: it fetches the data and fills an object, while the second one fetches the data, fills an array and then casts the array to the object.
You could also look at http://us.php.net/manual/en/pdostatement.fetchobject.php

Method stmt->fetch(); return an indexed array (PDO::FETCH_BOTH) by both column name and zero-indexed array and $stmt->fetch(PDO::FETCH_OBJ); method returns anonymous object with property names that correspond to the column names returned in your result set.

Related

What does the while loop do for the pg_fetch_array($result) such that you get next rows and end

I'm a php dev, been coding all this while with the help of postgresql. I searched the web, but couldn't find an answer. I'm really curious. In this code below, where is the 'true' flag stored? Isn't the argument for while loop supposed to be a comparison statement which returns a boolean value, instead of a variable/array assignment statement? I plan to use the correct answer to find better ways to code my app and impress my boss.
$result = pg_query($query);
while($myrow = pg_fetch_array($result)){
$var1 = $myrow[0];
$var2 = $myrow[1];
//do some magic with the variables
}
Based on official docs of pg_fetch_array()
An array indexed numerically (beginning with 0) or associatively
(indexed by field name), or both. Each value in the array is
represented as a string. Database NULL values are returned as NULL.
FALSE is returned if row exceeds the number of rows in the set, there
are no more rows, or on any other error.
So if there is no more rows it returns FALSE, if there is a rows return numerically or associative array which while loop evaluates to TRUE.

How do I make execute with PDO output a string rather than a single-element array?

I want to select a field in my mysql database containing values separated by commas (let´s say it´s "dd,bb,ee"), so that these can be exploded and turned into an array.
However, if trying to do this:
$sql = $conn->prepare("SELECT contacts FROM Users WHERE username = ?");
$sql->execute($usernametmp);
$oldcontacts = $sql->fetch(PDO::FETCH_COLUMN);
I get this error:
Warning: PDOStatement::execute() expects parameter 1 to be array, string
given in /.../.../.../.../.../....php
on the execute line, whereas if I do the following:
$sql = $conn->prepare("SELECT contacts FROM Users WHERE username = ?");
$sql->execute(array($usernametmp));
$oldcontacts = $sql->fetch(PDO::FETCH_COLUMN);
it works, but with the db entry coming out as one array element containing "dd,bb,ee", where it´ll need to be a string in order for me to use explode on it with the comma as a delimiter.
Any idea how to fix this?
I believe the PDO fetch function returns an array, not a scalar, even if the row contains a single column.
(I'm not at all familiar with the PDO::FETCH_COLUMN style with the fetch function. Is that documented somewhere? I think that style can be used with the fetchAll function. But that will still return an array.)
The PDO fetchColumn function will return a scalar, rather than an array.
Reference: http://php.net/manual/en/pdostatement.fetchcolumn.php
(And passing bind parameters into the execute is separate unrelated issue.)

How can I free mysql result straight fetched as an array and stored in a variable?

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.

Clarification for using functions like row() and row_array(), etc

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

is it possible to make multiple fetch() actions on a single instance of PDOStatement Object?

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.

Categories