简体   繁体   中英

How to add variables to while loop results in php

Hello I know I am new to php and coding but I have looked for days in forums and videos and i still have not found a clear answer. I have searched thoroughly before I attempted to bother you kind people.

I have 3 divs

<div id="left_div"></div>
<div id="middle_div"></div>
<div id="right_div"></div>

I have a while loop that outputs some color data into left_div

$query = mysql_query("SELECT * FROM colorstyle");
while($data = mysql_fetch_array($query)){
echo "$data[1]";
 }

when I echo data my results are

blue

red

green

purple

and so on, and if the user do not see their color they can update the database's color table.... nothing new all this code works fine.

Note* The color database is accessible to all users

In the middle_div I have a form with ADD and Delete Buttons


The Process:

The user goes to the color_update_page.php

The left_div show the available colors from the global database.

The right_div shows the colors the user selected from the global database and added to their color table in the database

When the user sees a color they want to add in the left_div , they click the color, then click the add button in the middle_div , and it adds it to the table in their color database in the right_div


How I tried to accomplish this

To make the while loop results clickable I used html and added a button to the output

$query = mysql_query("SELECT * FROM colorstyle");
while($data = mysql_fetch_array($query)){
echo "<button value=\"$data[1]\" > </button><br>";
 }

To get the value of the button to a form I added an input field next to the button with the button value, this way i wouldn't have to worry about the user having to fill out a value into the input field...so now it look like this

$query = mysql_query("SELECT * FROM colorstyle");
while($data = mysql_fetch_array($query)){
echo "<input type='text' value=\"$data[1]\"><button value=\"$data[1]\" > </button><br>";
 }

next step I was going to have a hidden input to capture the value of the echoed input field..... so now the code looks like this

$query = mysql_query("SELECT * FROM colorstyle");
while($data = mysql_fetch_array($query)){
echo "<input type='text' value=\"$data[1]\"><button value=\"$data[1]\" > </button>
<br>";
 }

   <input type="text" value="" style="display:none">......  lets call this this_will_change

I was then going to use javascript and an onclick function to change the value of the userInput .... So when the user clicks the echo generated button, the value from the echo generated input is transferred to and changed the field thats hidden... Then when the add button is clicked the users color table is then updated...

Heres the javascript and the corresponding php...

Please Note: id='userInput' was added to the generated input tag....and id="this_will_change" was added to the hidden input field.

<script type=\"text/javascript\">
   function changeText2(){
   var userInput = document.getElementById('$data[1]').value;
   document.getElementById('this_will_change').innerHTML = $data[1];
   }
</script>

<?php
       $query = mysql_query("SELECT * FROM colorstyle");
while($data = mysql_fetch_array($query)){
echo "<input id='userInput' type='text' value=\"$data[1]\"><button value=\"$data[1]\" onclick='changeText2()'  > </button>
<br>";
 }

   <input type="text" value="" style="display:none" id="this_will_change">......  
?>

The Problems I faced:

I did not know I can not access data outside of a while loop array.... so I added the code inside the echoed while loop. Not only was this messy when I looked at the view source code I could see that the javascript was repeated along with the while loop.

Also in order for it to work I would have to add the ADD and Delete forms to the while loop as well which looped and duplicate the form as well.

I tried to do a work around and put the while loop results into a variable with this

$query = mysql_query("SELECT * FROM colors");

while($data = mysql_fetch_array($query)){
echo "$data[0]";
$results[] = $data['0']
}
$results = implode("<br> ",$results);
echo "<button>$results</button>";

This woks but it echos the entire array into one large single button... not like before when all the results of the array were separated..


What I am asking?

How can I dynamically add a variable to each result from the while loop.. Since I have no idea what colors a user will want to add there is no way I can add a normal variable with a value unless I do it manually with the user adding colors then I would have to manually create the variable

Meaning if the results from the while loop are

Blue

Red

Orange and so on

How can I change that to

$blue = 'blue';

$red = 'red';

$orange = 'orange';

I know there has to be a way to get this done as i see similar versions on other websites. Like on iOffer.com. If there is a country you do not want to sell to you can click that country in the left_div (the country is then highlighted)...then click add in the middle_div ..........and your list of restricted countries will be updated.


What I have looked into:

I've looked into variable variables but every keep saying those shouldn't be done and I didn't quite understand it.

I've read many ways on using AJAX but I am not there yet.

And yes, I know MySQLi, OOP, and jQuery are better for coding but I want to get a grasp on using mysql and javascript before i get to that. I want to code this website using mysql then upgrade the site using those techniques.. Please try to limit the responses to javascript if needed and mysql.

Apologies:

I am sorry for being long winded with my ignorance on php. But I have read so many times that the poster never gave a clear description of the problem they are having and what they are trying to accomplish. Hopefully I was clear and not irritating. Thank you in advance for your help.

Here is how it looks:

<head>
  <style>

 div{
 text-align:center;
 }

 li{
 list-style:none;
 }

 #color_select{
 overflow:auto;
 width:706px;

 #color_select li{
 float:left;

 #left_div{
 border:1px solid black;
 width:300px;

 #middle_div{
 border:1px solid black;
 width:100px;

 #right_div{
 border:1px solid black;
 width:300px;
}
 </style>
</head>

        <body>
<nav id="color_select">
    <ul>
       <li>
          <div id="left_div">
          <label>Available Colors</label>
          </div>
      </li>
      <li>
          <div id="middle_div">
          <label>Available Colors</label>
          </div>
      </li>
      <li>
          <div id="right_div">
          <label>Available Colors</label>
          </div>
      </li>
    </ul>
</nav>
</body>


</html>

Without using javascript at all , this is how I would consider tackling this:

  • Fetch your colours from the database into a single variable $colours
  • Get the colours that are selected already by accessing the POST vars ( $coloursSelected = $_POST['colours'] )
  • Begin your form ( <form method="post"> )
  • Create a div that is hidden ( style="display: none;" )
  • Loop through your colours and add them as checkbox elements in the hidden div ( <input type="checkbox" name="colours[]" value="{$colour}" /> ) - You will need to make sure that the selected="selected" attribute appears if it has been selected (in $coloursSelected )
  • Do your HTML for your three columns
  • In the first column you will loop the difference of all your colours and those that are selected ( $unselectedColours = array_diff($colours, $coloursSelected); )
  • Echo those colours to the page as buttons like the following:

    <input type="submit" name="added" value="{$color}" />

  • In the right hand column just loop the colours that are already selected and echo buttons in a similar way:

    <input type="submit" name="removed" value="{$color}" />

This is missing a few key steps because this isn't a "write it for you" website. You should add a var_dump($_POST) to your code so you can understand what's going on.

I hope that pushes you in the right direction.

Whenever you see you're repeating something, it usually means you're doing something wrong.

You approach is wrong here - no need to query the database so many times. You fetch the data once, put it into an array and then use that array all the time.

I see you've tried something like that here:

$query = mysql_query("SELECT * FROM colors");

while($data = mysql_fetch_array($query)){
echo "$data[0]";
$results[] = $data['0']
}
$results = implode("<br> ",$results);
echo "<button>$results</button>";

One echo will print one thing - and here it's one button with an imploded array. Not good. You want to loop over all the results and create a button for each. So:

$query = mysql_query("SELECT * FROM colors");

while($data = mysql_fetch_array($query)){
    echo "$data[0]";
    $results[] = $data['0']
}
for($i = 0; $i < count($results); $i++) {
    echo '<button>', $results[$i], '</button><br/>';
}

Now this will output something like:

<button>Blue</button><br/>
<button>Red</button><br/>
<button>Orange</button><br/>

A good idea here is to add some JavaScript controls over those buttons. Let's add an onclick handler that will call some function and pass the color index as a parameter. The modified loop now looks like this:

for($i = 0; $i < count($results); $i++) {
    echo "<button onclick='buttonClicked($i)'>", $results[$i], '</button><br/>';
}

And btw, jQuery is not better for coding than plain JavaScript - easier to learn, yes... but also slower and heavier (the size of the library), and in the end, it still uses plain JavaScript. You'll definitely be a better developer if you have a solid knowledge of JavaScript rather than just jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM