Jump to content

[SOLVED] using variables in another page


CyberShot

Recommended Posts

I have a test database set up on localhost. I have a form that I can type a name into, hit the button and it puts the name into the database and into a list on my page. it works fine. Now, I wanted to make a drop down list with all the names so that you could select one to remove that name from the database. So I did this

 

<form>
<select>
<option><?php echo $name ?></option>
</select>
</form>

 

  What that did was list the very last name in the list. What I thought it would do was list all the names based on the loop that I have set up to read all the names from the database. which is this

 

$mysql = new mysqli('localhost', 'myusername', 'mypass', 'mydatabase') or die('not working');

$result = $mysql->query("SELECT * FROM myTable") or die($mysql->error);

if($result)
{
while($row = $result->fetch_object())
{
	$name = $row->names;
	echo $name . "<br />";
}
}

 

  Now the while loop is in a file I called results and it is included in the index page with an include. I thought this would give me access to the $name variable and allow me to use it the same way it's being used in the loop. of course I was wrong, so how do I use it the same way?

Link to comment
https://forums.phpfreaks.com/topic/178304-solved-using-variables-in-another-page/
Share on other sites

Your while loop would need to make an array.

 

$name = array();
while($row = $result->fetch_object())
{
  $name[] = $row->names;
}

 

Then...

<form>
<select>
<?php foreach ($name as $n): ?>
<option><?php echo $n ?></option>
<?php endforeach; ?>
</select>
</form>

figured it out. I had to move the foreach loop out of the while loop and now it works. like this

 

$mysql = new mysqli('localhost', 'root', 'pascal35', 'data') or die('not working');

$result = $mysql->query("SELECT * FROM myTable") or die($mysql->error);

if($result)
{
$name = array();
while($row = $result->fetch_object())
{	
	$name[] = $row->names;

}
foreach($name as $n):

	echo $n . "<br />";
	endforeach;
}

 

is that propper coding for the foreach loop? I just copied the foreach loop that you posted above.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.