Using a variable outside of the while loop (scope) - php

Small problem regarding scope in PHP, I can't seem to call the variable $report outside of the while loop. I have tried various things, including return. This doesn't work, the only two functions that work here are if I echo the variable $report inside the loop, or if I print it. Which I do not want to do, although it solves the problem, but I don't want random gibberish on the user's screen.
I have been looking around for the last 15 or so minutes, and I haven't seen any problems quite like this one on here.
Any help would be appreciated.
<?
require "functions2.php";
require "members.php";
$query = "SELECT MAX(DOCid) as prevDOCid from reports";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$prevDOCid = $row[prevDOCid];
$thisDOCid = $prevDOCid+1;
$report = "a"."b".$thisDOCid;
}
echo $report;
?>

You could try to define the variable before the loop, e.g.
$report = "";
while ($row = mysql_fetch_array($result)) {
$report .= "a"."b".$row["prevDOCid"]+1;
}
echo $report;
I hope this helps you!
Edit Use .= not +=

Related

Show multiple results from PDO::FETCH_ASSOC

Iwas wondering if someone could help me?
I have a table called markers, in this table it stores multiple records each with a name etc. I would like to echo each name however the below code only shows one results. How can I show more than one. Can someone please help I am new to PDO.
$stmt = $dtb->query('SELECT * FROM markers');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName = $row['name'];
}
Use an array to hold the result, in your code, the variable $markerName is overwrote on each iteration.
$stmt = $dtb->query('SELECT * FROM markers');
$markerName = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
That is because you are overwriting it each and every time , use an array instead.
Rewrite like this...
$markerName = array(); //<---- Add here
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
echo implode('<br>',$markerName); //<---- Implode it up for display
Rewrite like this
$names = $dtb->query('SELECT * FROM markers')->fetchAll();
Being new to PDO, you are supposed to try tag wiki first, where you can find an answer not only to this one but to many other questions.

why doesn't my query work

My query stop working suddently. I know it is dutch but can you detect any errors?
There are no MySQL errors. He just won't write $content to the screen.
I tried numerous things. he just stop working
<?php
$activiteiten= "SELECT
activiteiten.ActiviteitID,
activiteiten.Naam,
activiteiten.plaatsen,
agenda.TijdBegin,
agenda.TijdEind,
agenda.AgendaID,
reserveren.ReserveringTijd
FROM
activiteiten,
agenda,
reserveren
WHERE
agenda.ActiviteitID = activiteiten.ActiviteitID
AND
agenda.AgendaID = reserveren.AgendaID
";
$result = mysql_query($activiteiten) or die(mysql_error());
$content .= '<tr>';
$content .= '<td>'.$record['Naam'].'</td>';
$content .= '<td>'.$record['ReserveringTijd'].'</td>';
$content .='<td>Beschikbare plaatsen:'.$record['plaatsen'].'</td>';
$agendaID= $record['AgendaID'];
$agendaData = agendaData($agendaID);
$content.= '<td>aantal reserveringen:'.$agendaData["reserveringen"].'</td>';
$content.= '</tr>';
}
You do a mysql_query, but you never fill the $record variable. How do you expect it to have content?
Try adding:
$record = mysql_fetch_array( $result );
after the mysql_query.
You need to understand these are two different things:
mysql_query will execute a query on the server
mysql_fetch_array (and friends) will get the results in the desired format.
If you only do 1, you execute the query. That works fine, but if you are interested in the results, you need to fetch them. Sometimes you don't need to (for example, when the query is a not a select).
There are no MySQL errors. He just won't write $content to the screen.
What about adding:
echo $content;
If you don't print it, then you won't see anything :)
Apart from that, aren't you mixing $result and $record?
Your code is missing mysql_fetch_assoc call after mysql_query, it should be something like this:
$result = mysql_query($activiteiten) or die(mysql_error());
while(false != ($record = mysql_fetch_assoc($result))
{
$content .= '<tr>';
$content .= '<td>'.$record['Naam'].'</td>';
$content .= '<td>'.$record['ReserveringTijd'].'</td>';
$content .='<td>Beschikbare plaatsen:'.$record['plaatsen'].'</td>';
$agendaID= $record['AgendaID'];
$agendaData = agendaData($agendaID);
$content.= '<td>aantal reserveringen:'.$agendaData["reserveringen"].'</td>';
$content.= '</tr>';
}
Stopped working and not printing out any error rises the suspicion that the data in the database has somehow changed and the query simply does not get any rows.
Execute your query in a database environment like phpMyAdmin and check if any rows are returned.
Otherwise check the other answers for mysql-php-related errors.
$result = mysql_query($activiteiten) or die(mysql_error());
while ($record = mysql_fetch_array($result, MYSQL_ASSOC))
{
// Your $record now contains the data you want
}
You have the query result stored in $result but you do not then go on to do anything with $result - you need to do something like:
$record = mysql_fetch_assoc($qry_result);
to retrieve the record results from $result. If you expect more than one result you'll need to use a while loop to loop through all the results
Change:
$content .= '<tr>';
To:
$content = '<tr>';
And remember to echo the $content on the page.
Make sure you have error reporting on so you see immediately if the problem lies in uninitialized PHP variable or somewhere else.

Print PHP variable name from mysql result

I have an array like this:
$lang = array();
$lang['ITEM0'] = 'Home';
Ok now, if I save the variable name $lang['ITEM0'] into a mysql and I try to echo the query results, it prints me $lang['ITEM0'] as a string and not as a variable, so how can I print the correct value 'Home' of the variable name from mysql?
Here the code:
while($row = mysql_fetch_array($r))
{
echo $row['name'];
}
//result: $lang['ITEM0']
//I want result: Home
Thanks :)
To save not a variable but only index would be a lot more sane solution.
while($row = mysql_fetch_array($r))
{
echo $lang[$row['name']];
}
God knows why you're storing variables in a DB like that, but I assume you mean you have the rows name stored as literally $lang['ITEM0'] (not the contents of that variable, the variable name itself.)
However, you'd do this:
eval("echo " . $row['name']);
But as other people have said, don't use eval. I would reconsider how you're doing this because it looks like a security nightmare waiting to happen.
BTW: If you feel you have to do it this way, at least use "Your Common Sense"'s method.
I came here is search of the same thing and later realized I already knew the answer was just searching to hard for something that was already there.
In your mysql statement save the name of your variable as something unique to you. Instead of $lang['ITEM0'] save it as {lang['ITEM0']} or any other unique. for example I have {userid}. However in your example you could then use in your php code:
So now we'll assume
$lang = array();
$lang['ITEM0'] = 'Home';
while($row = mysql_fetch_array($r))
{
echo $row['name'] ;
}
Here you get output of: I want to go {lang['ITEM0']}.
Change it to this:
$lang = array();
$lang['ITEM0'] = 'Home';
while($row = mysql_fetch_array($r))
{
$var = str_replace('{lang['ITEM0']}', $lang['ITEM0'], $row['name']);
echo $var;
}
You will get: I want to go Home
Hope this helps anyone who comes to this page.
Use variable variables:
echo $$row['name'];
Note the TWO $ signs.
PS. NEVER use eval ;)

PHP OOP Mysql Query

I'm quite new to PHP OOP and I have a question regarding a simple MYSQL query.
I have an index.php page where I want to output my results from my query.class file.
Here is my method,
public function Query($rowName) {
$q = mysql_query("SELECT * from p_tuts");
while($row = mysql_fetch_array($q)) {
echo $row[$rowName];
}
}
Now this works fine and I can call it though my index.php file
$Database->Query('tut_content');
But my issue is I want to wrap each content block in DIV containers and don't want to have to echo the HTML code in the class file, so I want to really echo the row's data in the index file, but unsure how to do this.
Kind regards
Pass the rows back as an array.
public function Query($colName) {
$q = mysql_query("SELECT * from p_tuts");
$rows = array();
while($row = mysql_fetch_assoc($q)) {
$rows[] = $row[$colName];
}
return $rows;
}
It's better this way anyway, because it keeps database code away from output code (i.e. echo).
Then output it like so:
<?php
$results = $Database->Query('tut_content');
foreach ($results as $result): ?>
<div><?php echo $result; ?></div>
<?php endforeach; ?>
You dont want to be doing the echo in your class.
You want to return the row...
This way
$Database->Query('tut_content');
Can be wrapped in the DIV / whatever you need...
OOP functions are the same as normal function. The function as you have it only echos $row[$rowname]. You either want to modify it to have it echo <div>$row[$rowname]</div> or have it return the row values as an array:
while($row = mysql_fetch_array($q)) {
$output[] = $row[$rowName];
}
return $output;
use the MVC pattern.
http://php-html.net/tutorials/model-view-controller-in-php/
the database belongs to the Model
Good Luck
Or you can use my favorite database layer http://dibiphp.com/. It's small but smart :-)

Easy method to print something, only once inside while loop?

I want to fetch information from one table and loop that until it's done, with the help of a while loop. Although, I want one column to be printed only once inside the loop.
There's two solutions I've come up with...
<?php
$i = 0;
// while loop start
if($i == 0){
// stuff to print
$i++;
}
// while loop end
?>
And ofcourse, I could just make another query before the while loop.
But these methods really aren't too efficient. Is there a less messy way to do this?
Actually, I'd be okay with running another query before the while loop, if it didn't get so messy, and perhaps if I could just re-use the query intended for the loop (I fetch everything from the table). I tried experimenting with mysql_fetch_field, but I'm not sure I get how it works, or if that even helps here * embarrassed *
Currently, the code looks like so:
$fetch = mysql_query("SELECT *
FROM `pms`
JOIN `pm_conversations` ON pms.ConvID = pm_conversations.ID
WHERE `ConvID`='".$_GET['id']."'");
$i = 0;
while($print = mysql_fetch_array($fetch)){
if($i == 0){
echo $print['Subject'];
$i++;
}
<table>
<th><?=$print['From']?>, <?=$print['DateSent']?></th>
<tr><td><?=$print['Message']?></td></tr>
</table>
}
If I understand your question correctly, I think you've got the right idea. I'm guessing you want to print something extra the first iteration (like maybe column headers using the array keys)?
$cnt= 0;
while($row = mysql_fetch_assoc($res)) {
if(0 == $cnt++) {
// first iteration only
}
// all iterations
}
Or, if I'm totally off a better description of what you're trying to do and the real world situation would help.
Have you thought about do...while? It has all of the benefits of while, plus it allows for code to conditionally happen before the first iteration.
$res = mysql_fetch_array( $resource );
// run the magical run once query/functionality/bunnies/whatever
// Hey, I'm tired. Let there be bunnies.
do
{
// put the regular while loop constructs in here;
}
while( $res = mysql_fetch_array( $resource ) );
$rs = mysql_query("SELECT * FROM tbl");
$row = mysql_fetch_array($rs);
do {
echo $row['column_name'];
} while($row = mysql_fetch_array($rs));
I don't know if this is what you need. Hope this one helps. =]

Categories