This question already has answers here:
fetch(PDO::FETCH_ASSOC only returning one row
(2 answers)
Closed 3 years ago.
I am trying to fetch image name stored in database and display it but it is not working? Can anyone please tell me what is wrong in below code:
<p class="phase-title-en">
<?php
$title="SELECT DISTINCT record_step_one FROM phase_one_data";
$vartitle=$dbh->prepare($title);
$vartitle->execute();
$result= $vartitle->fetch();
?>
</p>
<?php foreach($result as $fn_title) {
echo "<p> '".$fn_title['record_step_one']."'</p>";
}
?>
My database looks like this:-
Your main problem is that you are using the PDO fetch() method, which returns only the next row of the result set (in your case, the first row).
This way, when you do a foreach, you are actually iterating over the columns of your first row (and not over all the rows, as you intended).
So your code is probably throwing lots of error messages (actually E_NOTICES) telling you that you are trying to use a string as an array, because each of the values in the loop ($fn_title) are strings containing the values for the first row (5, 2, eagle, etc).
EDIT: Sorry, but in my original reply I didn't notice the DISTINCT keyword in your query. So actually, the foreach would run only once, and the value would be the string eagle. But still, the problem is the same, there is no index record_step_one inside the string eagle.
The first step towards your solution would be to replace fetch() with fetchAll(), and check for any other errors that may arise (for instance, we can't see where $dbh is being instantiated in your code, which may or may not be a problem).
Related
I made a while loop that will tell if there are items in the transaction history and will put it back in the inventory as the transaction ends but the problem is. It fetches an error called
Uncaught Error: Call to a member function fetch_assoc() on bool in
So I tried the query's one by one and it works.
I tried to experiment and comment the other query and adding a counter++; to tell if the loop works. The problem I found is that after the first if else the counter only add's 1 Where as if I only try this it loops 4 which is right
Query I tried to check the number of loops
$counter=0;
$sql="SELECT * FROM brb_backtransaction WHERE trans_uk='$curr_trans' ";
if($rs=$con->query($sql)){
while ($row=$rs->fetch_assoc()){
$counter++
}
}
It echoes 1234 so it's correct but when the first if else happen it only echo'es 1
$counter =0;
$sql="SELECT * FROM brb_backtransaction WHERE trans_uk='$curr_trans' ";
if($rs=$con->query($sql)){
while ($row=$rs->fetch_assoc()){
$item = $row['trans_item'];
$quan = $row['trans_quantity'];
$sqlsitem="SELECT itmQuantity FROM brb_inventory WHERE itmName='$item'";
if($rs=$con->query($sqlsitem)){
$quanrow = $rs->fetch_assoc();
$currquan = $quanrow['itmQuantity'];
$counter++;
}
I remove other query's as I think this is the problem I ran a total of 3 queries in the while loop.
For your while loop to work it needs access to your original data stream as stored in the $rs variable.
However, further down in your code you are replacing the contents of the $rs variable with a totally new data stream. Therefore, the while loop no longer has access to the original data stream as it is basically throw away.
To solve this, change the second instance to another variable name such as $rs2. That way you have two completely different variables for two different data streams.
With that said, your code is also open to injection attacks. I would recommend looking into PDO and prepared statements.
Also, Tangentially Perpendicular is correct in using SQL JOINS
I've a problem with my code. I can't wrap my head around what's wrong with the code or where I fail.
I basically want to calculate the average of multiple numbers from my database from one column.
/*data calculation*/
$calculation = "SELECT AVG(current) FROM offset_items";
$calculation_result = mysqli_query($connect, $calculation);
if($average = mysqli_fetch_assoc($calculation_result))
{echo "Average: ".$average["current"]."<br>";}
The problem here is, that I get only a blank displayed after the "Average: ".
But if I remove the AVG from the query, I get all results listed of that DB column. The DB contains data, which I import in the same script, as well as displaying them for testing.
I get the following error, which is the line of the echo:
Notice: Undefined index: current in C:\MAMP\htdocs\Offset_Items.php on line 50
I think the problem here is the mysqli_fetch_assoc, but I'm not sure.
Digging through the multiple topics about that "Undefined index" didn't solve my problem. Even when I declare the variable before as NULL.
I'm out of touch with programming, but currently picked it up again to code some tools for work. So if you guys could help me, I would be really thankful.
The PHP code that attempts to print the result reads:
$average = mysqli_fetch_assoc($calculation_result);
echo "Average: ".$average["current"]."<br>";
but the query that generates the result set does not contain any column named current.
Use an alias for the expression AVG(current) in the SELECT clause to get a column in the result set having the desired name:
SELECT AVG(current) AS current FROM offset_items
I'm currently working on a website with a friend and I need to display the average rating for a movie.
So, I have a database with numerous columns (name, mail, etc) including "note".
My friend wrote this code :
<?php
$moyenne = "SELECT avg(note) FROM `annee_1`";
$test = $db->prepare($moyenne);
$test->execute();
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
echo $resultat;
?>
I'm not overly familiar with php or mysql. I know something is wrong (since this doesn't display a number, but just "Array"), but I don't know what.
Any suggestiong, or solution to my problem?
Thanks ! :)
You can access to your result by passing parameter to your array with a while loop. Replace your echo $result by print_r($resultat) and you can check the result you have received.
Your query will return one row with one column. An easy way to get a single value from a query like that is to use
$resultat = $test->fetchColumn();
Instead of
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
You're seeing "Array" currently because $resultat is an array (because that's what fetchAll reutrns), and when you try to echo it, it gets converted to a string. In PHP, the string representation of any array is "Array". See the documentation here:
Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array.
But if you use fetchColumn() instead, $resultat won't be an array. Based on your comments, it should be an int.
I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:
id, model, manufacturer, url, date_modified
My test code is as follows:
<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>
I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.
Many thanks in advance for any advice, I'm sure I'm just missing something stupid.
I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
printf function needs a string as the first parameter, see:
http://php.net/manual/en/function.printf.php
Use for instance var_dump instead:
var_dump($sqlresult);
This question already has answers here:
fetch single record using PHP PDO and return result
(2 answers)
Closed 6 years ago.
I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.
My Problem
User types a numeric code into the search box, translates it to
.php?code=term
Script selects all columns from the database where the code is the
code term searched for.
PHP will Echo the results
My Code
if (isset($_GET["code"])) {
//IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
$crimecode = $_GET["code"];
$crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
$crcode->bindParam(':code', $crimecode);
$crcode->execute();
$coderesult = $crcode->fetchAll();
echo "<h4>CODE:</h4>";
echo $crimecode;
echo "<br /><h4>DEFINITION:</h4>";
echo $coderesult;
die();
}
Before, it was simple. All I had to do was:
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.
Right now, the above PDO code returns definition: ARRAY.
Like literally, the $coderesult prints Array.
The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).
$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.
I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:
$coderesult = $coderesult[0];
Then you can
echo $coderesult['definition'];
If you're trying to get more than one row, you need to use foreach to loop through the array.
I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.
Also, I think it's worth to mention that your previous code
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
it's vulnerable to SQL Injection.