Newbie to PHP and trying to learn it. I have returned data from my DB.
So the rows may look something like below
ID--------Name--------PhoneNo
1 Joe 1234
2 Jane 5678
3 Tom 0000
I am using the msql_fetch_array to return the data as below:
<?php
while($row = mysql_fetch_array($result))
{
$NameOne = $row['Name'];
}
?>
This is placing the name 'Joe' in the variable name NameOne as expected. What is the best way however to get Jane and Tome into variables called $NameTwo and $NameThree that I can then echo these variables further down in my html and similary I want to place the phone number retrieved into seperate variables and refer to them later in my html.
The ideal approch will be saving them inside an array, which can be achieved like this:
$Names = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$Names[$i] = $row['Name'];
$i++;
}
Now you can retrieve your data this way:
echo $Names[0]; // Will output the first name saved.
If you want to really persist the results, store them in an array:
<?php
$data = array();
// Note that I've changed "mysql_fetch_array" to "mysql_fetch_assoc" to decrease the number of saved data.
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['Name'];
}
/* Now you can use the data wherever you want, like: $data[0]['Name'] for first name, $data[1]['Name'] for second name and so on */
?>
Rather than creating so many new variables, why not create an array?
<?php
$i=1;
while($row = mysql_fetch_array($result))
{
$Names[$i]= $row['Name'];
$i++;
}
?>
You can then use the array in your code
echo $Names[1]; // 1 or 2 or 3 etc
For multiple attributes you can use a multidimensional array
$i=1;
while($row = mysql_fetch_array($result))
{
$Data[$i]["Name"]= $row['Name'];
$Data[$i]["Phone"]= $row['Phone'];
$i++;
}
You can then use the array in your code
echo $Data[1]["Name"]; // 1 or 2 or 3 etc
You can directly place html inside your while
loop
<?php
while($row = mysql_fetch_array($result))
{
?>
<div><?php echo $row['Name']; ?> </div>
<div><?php echo $row['PhoneNo']; ?> </div>
<?php }
?>
You can add the details to another array
<?php
$names = array();
$phnos = array();
while($row = mysql_fetch_array($result))
{
$names[] = $row['Name']; //$names[0] , $names[1] etc..
$phnos[] = $row['PhoneNo']; //$phnos[0] , $phnos[1] etc..
}
?>
To strictly answer KOL's question:
<?php
$i = 0;
$numbers = array('One', 'Two', 'Three', 'Four', 'Five');
while($row = mysql_fetch_array($result)) {
if($i++ > count($numbers) {
throw new NotMoreNumbersSupportedException();
}
$varname = 'Name' . $numbers[$i++];
$$varname = $row['Name'];
}
var_dump($NameOne, $NameTwo, $NameThree, $NameFour, $NameFive); //etc
?>
Now shoot me.