I am trying to migrate from mysqli procedural to PDO because my website was halfway, half in pdo, and the rest in mysqli procedural, now I want to shift to PDO completely. Here is an example of the code I run
$rowNum = 0;
foreach ($result->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_OBJ) as $row) {
$rowNum = $rowNum + 1;
$dbUsername = $row['Username'];
}
if ($row>0) {
echo $dbUsername;
}
But in some scenarios, the code gives me an error that trying to get property 'Username' of non-object
I know it was possible to use only ($result->fetchAll(PDO::FETCH_ASSOC)
But doing this ($result->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_OBJ) becomes a need as some context of the code I'm modifying use the symbol like $row->Usename and the other use $row['Username'], How can I make it accept both modes as shown above?
I tried to use PDO:: FETCH_BOTH but the problem persists.
As #YourCommonSense pointed out in his comment, you can use PDO::FETCH_LAZY to accomplish this. However, you cannot use that with fetchAll, only with fetch:
while ($row = $result->fetch(PDO::FETCH_LAZY)) {
// Both of these will work
$username = $row['Username'];
$username = $row->Username;
}
If you really want to use fetchAll, you'll have to fetch the rows as one type and cast them back and forth between arrays and objects:
foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
// with PDO::FETCH_ASSOC, $row is an array
$username = $row['Username'];
$row = (object)$row;
// $row is an object now
$username = $row->Username;
$row = (array)$row;
// $row is now an array again
$username = $row['Username'];
}
It's not possible. You cannot get both at the same time. There would be no way to represent such a result in PHP.
When you try to use both with PDO::FETCH_ASSOC|PDO::FETCH_OBJ you are actually fetching the result as PDO::FETCH_COLUMN. That's because fetch parameter is a bitwise flags parameter. When you do an OR operation on these flags it is the same as 2|5 = 7. 7 is the value for PDO::FETCH_COLUMN.
I don't know what use case you have for this, but it sounds like an XY problem. If you use fetchAll() you cannot have it both as an array and an object. But if you are fetching it row by row with fetch(), you could fetch each row in a different way.
$res = $pdo->query("SELECT 1 as foo UNION ALL SELECT 2 as foo");
var_dump($res->fetch(PDO::FETCH_ASSOC));
var_dump($res->fetch(PDO::FETCH_OBJ));
/*
Outputs:
array(1) {
["foo"]=>
int(1)
}
object(stdClass)#3 (1) {
["foo"]=>
int(2)
}
*/
Related
I am using prepared statements for the first time. And i cannot get the select to work.
For some reason, it returns all the records but i cannot get them into variables. I know it returns all the records because if i add echo '1'; to the loop it echo's 1 for each record.
Any assistance would be great. The code is below:
function builditems($quote_id){
if ($stmt = $this->link->prepare("SELECT * FROM `0_quotes_items` WHERE `quote_id` = ?")) {
// Bind a variable to the parameter as a string.
$stmt->bind_param("i", $quote_id);
// Execute the statement.
$stmt->execute();
while ($row = $stmt->fetch()) {
echo $row['id'];
}
// Close the prepared statement.
$stmt->close();
}
}
UPDATE:
in the error log, i see the following error after adding the while ($row = $stmt->fetch_assoc()) { like suggested:
PHP Fatal error: Call to undefined method mysqli_stmt::fetch_assoc()
I found a link that the same issue was had, but i do not understand how to implement the fix.
Any assistance would be great, with regards to a example.
How to remove the fatal error when fetching an assoc array
The PHP MySQLi fetch method does not access query data using brackets notation: $row['id'].
So I see two options to remedy: first find this line:
while ($row = $stmt->fetch()) {
...and modify it to, either, first add the bind_result method, and then access the data a bit differently:
$stmt->bind_result($id, $other, $whatnot); // assuming 3 columns retrieved in the query
while ($row = $stmt->fetch()) {
echo "$id $other $whatnot<br>";
}
...or, first access the result object's fetch_assoc method and use fetch_assoc instead of fetch:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
Now you can use table column names as keys to access query data in your loop: $row['id'].
PHP MySQLi method fetch requires you to use bind_result. Doing this allows you to call your data by the variable names you've bound it to.
To use the field name as the result array index, such as: $row['id'], you need to use the PHP MySQLi fetch_assoc method. And to use fetch_assoc you need to first get the result object in order to access the fetch_assoc method.
Following is a typical OOP way to Connect and Retrive data from MySQL database using MySQLi and PHP.
Now I am a little bit confused on using the pure PHP arrays at this example:
Can some one please let me know if the $result is array or not? I mean in
$result = $mysqli_coonect->query($sql);
if so how come we didn't use the array() function or [] to create it?!
same thing happening with $row at:
$row = $result->fetch_assoc()
I am asking this because in order to load $row; to $results[] at $results[] = $row; we declared the $results as an array explicitly before the while() how come we are not doing this for other or vice versa?!
<?php
$mysqli_coonect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
$sql = "SELECT * FROM books WHERE id <= 10";
$result = $mysqli_coonect->query($sql);
if (($result) && ($result->num_rows > 0))
{
$results = array();
while ($row = $result->fetch_assoc())
{
$results[] = $row;
}
$result->free();
}
$mysqli_coonect->close();
Always refer to the PHP documentation. It's great and you can easily find what you want.
http://php.net/manual/en/mysqli.query.php states that a query will return mixed in this case meaning either false if the query failed or mysqli_result object of the query was successful.
Getting down to business
$result = $mysqli->query($query) returns a mysqli_result object. This means that $result is now an object.
We then call the method fetch_assoc from our newly created $result (mysqli_result) object and store the results of the method in the variable $row (which if the method is successful will be an array). If you look at what fetch_assoc returns (http://php.net/manual/en/mysqli-result.fetch-assoc.php) you see that it returns an array.
We loop through our newly created $row array.
I've been running the query oh phpMyAdmin and it shows all the rows, but my query in php only returns the first row.
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
print(count($result)); //always returns 1
for ($x = 0; $x < count($result); $x++) {
$row = mysqli_fetch_row($result);
}
For reference, here's why count() is returning 1. From the manual:
If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable [the parameter] is NULL, 0 will be returned.
Since $result is a resource (object) that is returned from your query, not an array which you would get within your loop getting the actual data out of the resource, count($resource) will return 1.
Your solution is of course to use mysqli_num_rows(). To retrieve data from this resource, you need to loop over it as you are doing, but either use mysqli_num_rows() in place of count(), or other (more common) ways of looping through a result set, like so:
while($row = mysqli_fetch_row($result)) {
// do stuff
}
You have to use mysqli_num_rows($result) function to count rows which are returned by MySQLi query.
Try this
echo mysqli_num_rows($result);
while($row = mysqli_fetch_row($result)) {
// write your code...
}
Use this instead of the for loop
the first thing that the query method returns to you is a resource/object. This query method always return a mysqli_result object for successful queries using SELECT, SHOW, DESCRIBE or EXPLAIN queries . For other successful queries mysqli_query() will return TRUE. For that reason it always count it as "1", what you should try is:
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
$numRows = $result->num_rows;
print(count($numRows)); //it should show you the total amount of rows
//verify the amount of rows before of tryng to loop over it
if ($numRows) {
while($object = mysqli_fetch_object($result)){
//for each loop you will have an object with the attributes of the row
echo $object->song_name;
}
}
This should work,
Regards.
I am trying to fetch a row from my mysql DB using mysqli query.
PHP
$_SESSION['orderID'] = "632";
$orID = $_SESSION['orderID'];
$sql = $db->prepare('SELECT * FROM order_list WHERE order_id = ? ');
$sql->bind_param('s',$orID);
$sql->execute();
while($row = $sql->fetch())
{
$productid = $row[0];
$name = $row[1];
echo $price = $row[2];
}
give no error in console and no result,
I have been trying to check the answers on stack overflow, I also googled it but all the suggestions gives me the same error.
I am pretty new with mysqli, your help will be highly appreciated
mysqli_fetch_array is a mysqli_result method not a mysqli_stmt one
You could use ->fetch() upon a mysqli_stmt
So basically your code could change that way
while($sql->fetch()) {
//do something
}
but you need to call bind_result() before looping (otherwise you can't access returned values)
I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?
Code:
//Get active listing IDs
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());
if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};
Thanks,
Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.
while($row = mysql_fetch_array($active)) {
// Your code here
}
Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.
In PDO it's rather straight forward:
$rows = $conn->query($active)->fetchAll();
See PDO::queryDocs and PDOStatement::fetchAllDocs.
With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.
Code for mysqli
$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
$rows = $result->fetch_all();
}
with PDO it's nearly the same
$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
$rows = $result->fetchAll();
}