I have while loop in a PHP file and outside of that, I have one variable. When I try to add this variable into while, it doesn't work.
example code:
<?
$var1 = 2999288;
while($row = mysql_fetch_array($result)){
echo $var1;
}
?>
Can anybody tell me a solution, how to echo that variable into a while? Or what I'm doing wrong?
Your SQL query is not returning any rows, make sure that your query is working properly before echoing results. Also please look into prepared SQL statements, they are more safe than the traditional way that you are using.
Related
I was trying to achieve something simple and was wondering if it was possible. Google search proved unhelpful this time. Probably it's not possible, but I am not sure. I have the following code:
<?php
//Enter your code here, enjoy!
$query1="yay";
$query2="it";
$query3="works";
for($x=1;$x<=3;$x++){
$query="\$query".$x; //I need to assign the above variables
echo $query;
}
?>
I want the output to be "yayitworks" but instead I get "$query1$query2$query3". Is there any way to get my result? I know a switch statement will help me achieve this, but am just curious.
Thanks in advance...:-)
What you want is variable variables: http://php.net/manual/en/language.variables.variable.php
$query = ${"query".$x}
This question is just for me to learn from. I can easily resolve it outside of the echo...but there MUST be a way to perform a basic calculation or function call within an echo statement...right?
$CurrentMembershipYear = '2016';
echo '<h2>Two-Year Membership for '.$CurrentMembershipYear.' and '.intval($CurrentMembershipYear)+1.'</h2>';
This should be echoing "Two-Year Membership for 2016 and 2017" but instead is generating errors. Usually I would just pre-calculate the second value before the echo statement and just pass it as a variable...but surely there is a way to put this calculation inline?
never mind...bone-headed brain asleep. Just needed parenthesis...I had only tried curvy braces:
$CurrentMembershipYear = '2016';
echo '<h2>Two-Year Membership for '.$CurrentMembershipYear.' and '.(intval($CurrentMembershipYear)+1).'</h2>';
parenthesis should solve it
(intval($CurrentMembershipYear)+1)
I've developed a habit of renaming my SELECT statement variable and I'm interested to know if it is necessary or not.
Here some typical code that I use:
$sql = ("SELECT * FROM tbl_one");
if(!$result_sql = $mysqli->query($sql))
{
// Error code here
}
while($a = $result_sql->fetch_assoc())
{
echo $a;
}
$sql2 = ("SELECT * FROM tbl_two");
if(!$result_sql2 = $mysqli->query($sql2))
{
// Error code here
}
while($b = $result_sql2->fetch_assoc())
{
echo $b;
}
For some reason I'm afraid there will be issues if I reuse the same $sql variable over again unless I rename it.
It's always good to have a different different variable for each statement you have as per coding standards even though PHP does not mind using same variable again and again.
It's just a string, so you shouldn't care. Its fine to use the same variable again if you don't need the previous value anymore.
Theoretically I opt not to reuse variable names for this sort of code, because of the risk of accidentally not overwriting one of them and getting strange results.
Then again, that problem doesn't go away just because you try to force yourself to remember to increment a number stuck on the end of the variable name.
Over time, as my code has improved, I've found that I very rarely need or want to execute multiple MySQL queries within a single PHP function, so the problem goes away entirely.
tl;dr: If I had a gun to my head, though... yes, I'd probably do it the same way you did. It's entirely subjective, though.
What is wrong with this code? I am trying to return an array and use it in the caller function.
function my_subjects()
{
$all_my_teams=my_teams();
$k=0;
$_subjects=array();
while($team=mysql_fetch_assoc($all_my_teams))
{
$q="SELECT $this->user_field FROM $team";
$r=mysql_query($q);
while($i=mysql_fetch_assoc($r))
{
$_subjects[k++]=$i;
}
}
return $_subjects;
}
Note: the function my_teams() returns the value similar to the $r variable which is used through all_my_teams variable. it contains all the names of teams.
Turn up error_reporting to see if your code is generating errors.
Check if your query is successful if( ! $r=mysql_query($q) ) { die(mysql_error()); }
var_dump($_subjects); to see if the data is what you expect it to be.
Maybe actually tell us what's going wrong? You've just posted a block of code and told us "it doesn't work." which isn't terribly indicative of a problem.
$k is irrelevant, just use $_subjects[]=$i;. [wouldn't cause an error, just easier]
Stop using mysql_* functions and port your code to PDO or MySQLi to:
Benefit from parameterized queries which can help protect against SQL injection.
Stop everyone on SO starting an unrelated argument in the comments about it.
while($i=mysql_fetch_assoc($r))
{
$_subjects[k++]=$i;
}
Here you also have to provide a field name for $i. Something like
while($i=mysql_fetch_assoc($r))
{
$_subjects[$k++]=$i["field_name"];
}
Array returning part is just fine.
Edit: Your variable k was missing a $ sign as well.
$_subjects[$k++] = $i;
should be fine, since you're using mysql_fetch_assoc() $i will contain an associative array of the result set.
If this is returning an empty array (is that the correct problem?), you should double check that your sql is correct and actually returning data/data that you expect.
Edit: Like Hanky Panky mentioned, 'k' is missing a $ sign in your code - that is likely to be your problem - PHP should be throwing a parse error for that one, so make sure you have error_reporting() enabled.
I usually try to minimize calls to MySQL where possible, but I've finally encountered the case where I have to do multiple calls to MySQL in a single script.
It looks like you can't use mysql_fetch_assoc twice in a single script(!).
It seems that mysql_data_seek is the solution, but I cannot seem to get it to work.
To be clear, I have two queries I need to make. The second query depends on results from the first... Here's the structure:
$result = mysql_query($query1);
while($row = mysql_fetch_assoc($result)){
$pos = $row['position'];
}
mysql_free_result($result); // result freed per comment below.
$query2 = ' '; //... dependent on $pos - in mysql shell this returns results!
$result2 = mysql_query($query2)
while($row = mysql_fetch_assoc($result2)){
echo $row['id'];
}
What happens above is that the second while loop returns no results even though the query should have nontrivial rows.
Just to be sure:
Is this how you clear the pointer from the previous result to be able to use mysql_fetch_assoc again?
mysql_data_seek($result,mysql_num_rows($result) - 1);
I'm not sure what to use as the second argument. Admittedly, I am not that clear on pointers, but it seems I should clear the pointer to 0. But I get this error:
Offset 0 is invalid for MySQL result index 8 (or the query data is unbuffered
Check your connection with mysql_error() and see if you're getting the "commands out of sync" error. If so, you need to call mysql_free_result() after completing the first query and before starting the second. You could also just call mysql_close() to close your database connection and then reopen a new one.
For more details, see this question.
OP changed the question, so see the edit
*Deleted the posted codes here**
EDIT
After your edited your question and made clear you have actually 2 resources it looks like there is something else wrong. You don't have to worry about pointer when you use two different resources to supply mysql_fetch_assoc(). The thing with mysql_fetch_assoc() is that it takes your param ($result) by reference.
Now to answer your question:
I usually try to minimize calls to MySQL where possible, but I've finally encountered the case where I have to do multiple calls to MySQL in a single script.
Nothing wrong with multiple SQL calls in one script. Although in general you should try to minimize the SQL calls (because they may hurt performance).
It looks like you can't use mysql_fetch_assoc twice in a single script(!).
Plain wrong. Ofc you can do it. As long as you note the above. However when you have two result sets this wouldn't be your problem.
It seems that mysql_data_seek is the solution, but I cannot seem to get it to work.
Again: this has nothing to do with it when you use two (different) result sets.
To be clear, I have two queries I need to make. The second query depends on results from the first.
This shouldn't be any problem at all. It looks like is something else wrong. Have you verified that the second query really is what you think it is? Are you sure there are records? Are you sure there aren't any (MySQL) errors. Do you have error reporting enabled? Have you tried printing out mysql_error()? To better be able to help you can you please provide your real code and not etc etc stuff? Maybe something else is going on.
Or maybe you are simply trying to run the second query inside the first loop. Which would be bad in so many ways.