I am trying to use a for loop to select an incremental value with a MySQL query. I have included sample code below:
<?php
$day_1="sep_28";
$day_2="sep_29";
$day_3="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
//$dayVarCount = $dayVar."_count"; // Don't really need this anymore, so removed.
$dayVarCount = $row[$$dayVar];
echo "$$dayVar.': '.$dayVarCount<p>"; // Edited.
}
}
?>
I think I am getting close, but when I run the code my page is showing this:
$day_1.': '.0
$day_2.': '.2
$day_3.': '.5
Any additional recommendations? Thanks for the great help!
Try a variable variable:
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
$dayVarCount = $dayVar."_count";
$$dayVarCount = $row[$$dayVar];
echo $$dayVar.': '.$$dayVarCount.'<p>'; // Edited.
}
This basically uses a string to reference a variable by its name.
Just think of it this way:
$variable = 'hello';
$string = 'variable';
echo $$string;
// Is the same thing as:
echo $variable;
// Because you can thing of $$string as ${$string} ---> $variable when {$string} is interpreted into 'variable'
http://php.net/manual/en/language.variables.variable.php
Replace this line:
echo "$$dayVar.': '.$dayVarCount<p>";
with this:
echo $$dayVar . ': ' . $dayVarCount . '<br>';
<?php
$day_1="January 1";
$day_2="January 2";
$day_3="January 3";
$query = mysql_query("SELECT * FROM dates WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$var = $."day_".$i;
$day_$i_count=$row['$var'];
echo "$day_$i: $day_$i_count<p>";
}
}
?>
You can try this code too.
That all seems overly complicated, but possibly I don't understand the question adequately. Would this work?
$day[1]="sep_28";
$day[2]="sep_29";
$day[3]="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
foreach ($day as $day_str)
{
echo $day_str . ':' . $row[$day_str] . '<p>';
}
}
Related
I would like to show 3 random images from database in my website. Below is its code:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd () {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd();
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd();
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
But whenever I run this code, I get the error below:
Undefined variable: my_array in line ... // The first line of makernd() function.
But I expected $my_array to be an accessible array for this function.
What's the problem?
To simply fix your problem, you should pass $my_array to makernd() as a parameter:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd ($my_array) {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd($my_array);
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd($my_array);
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
HOWEVER, I strongly suggest putting the randomization in MySQL, to
Simplify your code
Significantly improve the performance, and
Eliminate excessive loops & recursion in PHP
Example:
$sql = "SELECT id,url
FROM tbl_gallery2
ORDER BY RAND()
LIMIT 3";
$query = mysql_query ($sql);
if (mysql_num_rows($query) >= 3) {
while ($r = mysql_fetch_row($query)) {
echo '<img src="./images/slider/' . $r[1] . '.jpg" alt="" class="slider" />';
}
}
PS - I also suggest you update your code to use mysqli, as mysql is deprecated
PPS - I also suggest you look into mysqli_fetch_assoc so you can reference query results by name instead of index (e.g. $r['url'] instead of $r[1] - as if you ever change the order of your query, you will break references by index.
I'm asking MySQL for data, but it slows down the whole script. Yet I have no idea how to get this out of a loop. I tried converting it to PHP array but honestly after day of tries I failed.
<?php
$id = '1';
include_once 'include_once/connect.php';
for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
$xy = $x."x".$y;
$pullMapInfo = "SELECT value FROM mapinfo WHERE id='".$id."' AND xy='".$xy."'";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
if ($pullMapInfo3 = mysql_fetch_array($pullMapInfo2)) {
#some code
} else {
#some code
}
}
}
?>
How to get MySQL query $pullMapInfo2 out of loop to shorten loading it by asking once?
If you want to fire script on your localhost you can c&p whole thing :-)
I'm not sure what you have in your table, but considering you are basically looping through virtually everything in it, I'd say do a single query for the given Id and then sort out what you need from the larger dataset.
Especially if you are always pulling back essentially the complete dataset for each id, there's no reason to even bother with the IN query, just pull it all back into a single PHP array, and then iterate through that as needed.
Use a MySQL IN clause
<?php
$id = '1';
include_once 'include_once/connect.php';
// first we create an array with all xy
$array = array();
for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
$xy = $x."x".$y;
$array[] = $xy;
}
}
$in = "'" . implode("', '", $array) . "'";
$pullMapInfo = "SELECT xy, value FROM mapinfo WHERE id='".$id."' AND xy IN ({$in})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
// we create an associative array xy => value
$result = array();
while (($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) !== false) {
$result[ $pullMapInfo3['xy'] ] = $pullMapInfo3['value'];
}
// we make a loop to display expected output
foreach ($array as $xy)
{
if (array_key_exists($xy, $result)) {
echo '<div class="castle_array" style="background-image: url(tiles/'.$result[$xy].'.BMP)" id="'.$xy.'">'. $result[$xy] .'</div>';
} else {
echo '<div class="castle_array" id="'.$xy.'"></div>';
}
echo '<div class="clear_both"></div>';
}
?>
When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.
I have two tables which stored question and answer, as below script is used to fetch serialize answers and would unserialize each of it into an array as following:
while($ans_row = mysql_fetch_array($q_chkans)){
$answer = unserialize($ans_row["a_answered"]);
foreach($answer as $val){
for($i=0; $i<=3; $i++){
$r[$i] = $answer[$i];
}
}
for example, let said after an unserialize process, I get each array elements as below:
$r[0] = a
$r[1] = b
$r[2] = c
with those a, b and c, I want to assign each of them into another table loop, which was fetch it question, like below:
1) question a?
answer a.
2) question b?
answer b.
3) question c?
answer c.
but my code was always return all answer like
1) question a?
answer a b c.
2) question b?
answer a b c.
3) question c?
answer a b c.
Full code as below:
$ques_data = array();
$q_ques = mysql_query("SELECT * FROM ".$tb03." WHERE ques_section='".$sectid."' AND ques_status='1' ORDER BY ques_id") or die(mysql_error());
while($rows = mysql_fetch_assoc($q_ques)){
$ques_data[] = $rows;
}
$q_chkans = mysql_query("SELECT * FROM ".$tb08." WHERE a_usrid='".$_COOKIE["loggedId"]."' AND a_section='".$sectid."'") or die(mysql_error());
$numrows = mysql_num_rows($q_chkans);
$q_sect = mysql_query("SELECT * FROM ".$tb02." WHERE sect_id='".$sectid."' LIMIT 0, 1") or die(mysql_error());
$r_sect = mysql_fetch_array($q_sect);
$section = $r_sect["sect_id"];
echo "<div class='sect_list'><b style='color:#000;'>".sprintf("%1\$.1f",$no)." ".ucwords($r_sect["sect_title"])."</b></div>".$staff_txt;
foreach($ques_data as $ques_rows){
echo "<div class='ques_list'>
<div><b>".$sectid.".".$no."</b> ".ucwords($ques_rows["ques_title"])."</div>
<div class='ques_rmk'>".ucwords($ques_rows["ques_rmk"])."</div>
<div class='answer'>";
if($numrows <= 0){
$q_ans = mysql_query("SELECT * FROM ".$tb04." WHERE input_ques_id='".$ques_rows["ques_id"]."'") or die(mysql_error());
if($ques_rows["ques_type"] == 1){
echo "<select name='txtOpt_".$section."_".$no."'>";
while($ans_rows = mysql_fetch_array($q_ans)){
echo "<option value='".$ans_rows["input_mark"]."'>".$ans_rows["input_title"]."</option>";
}
echo "</select>";
}else{
echo "<input type='text' name='txtbox_".$section."' value='' style='width:500px;height:18px;' />";
}
}else{
while($ans_row = mysql_fetch_array($q_chkans)){
$answer = unserialize($ans_row["a_answered"]);
foreach($answer as $val){
for($e=0; $e<=count($answer); $e++){
$r[$e] = $answer[$e];
}
}
}
}
echo " </div>
</div>";
$no += 1;
}
How can I make each of the answer could proper assign into its own question?
Please advise, Thanks!
Try this:
while($ans_row = mysql_fetch_array($q_chkans)){
$answer = unserialize($ans_row["a_answered"]);
foreach($answer as $i => $val){
$r[$i] = $val;
}
}
I am fetching a number of results from my database using a mysql_query. What I need to do is echo the result number, along with the result itself.
In other words, if my query fetches 3 results, I would like the first result to have a 1 beside it, and the second result a 2 and so on. I need the numbers to start at 1, not 0.
note: I do not mean mysql_num_rows as that only tells me how many results, not the result number itself.
Here is my query information:
$primary_img_query = "SELECT imgURL, imgTitle FROM primary_images WHERE primaryId=16";
$primary_img_data = mysql_query($primary_img_query) or die('MySql Error' . mysql_error());
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>";//this is where I want the result number echoed
}
Make a counter:
$count = 1;
while(...){
echo $count++;
}
In your case:
$count = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo $count++;
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>";
}
One other solution I don't see mentioned here is using an ordered list:
$result = mysql_query(...);
echo "<ol>\n";
while ($row = mysql_fetch_array($result))
{
echo "<li><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></li>";
}
echo "</ol>\n";
This gives you more "correct" HTML, if you don't particularly care about the result number in your PHP code. (Nothing stops you from using both, either: use an ordered list to output the number, but keep a counter for other things, like rel attributes or alternating CSS classes.)
Just do:
$counter = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>";//this is where I want the result number echoed
echo $counter++;
}
$i = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>" . $i;
$i ++;
}
$i = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>" . $i;//this is where I want the result number echoed
$i++;
}
A little bit brutish, but why not just keep a counter?
$primary_img_query = "SELECT imgURL, imgTitle FROM primary_images WHERE primaryId=16";
$primary_img_data = mysql_query($primary_img_query) or die('MySql Error' . mysql_error());
$n=0;
while($row = mysql_fetch_assoc($primary_img_data)) {
$n++;
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>" . $n;
}
Inline counters, for the win.
$i = 0;
while($row = mysql_fetch_assoc($primary_img_data))
{
echo ++$i . "<img src='new_arrivals_img/thumbnails/" . $row['imgURL'] . "'><br>";
}
This is not materially different than any other answer here, other than it's 1 line shorter and actually leverages the fact that you can use incrementors inline.