I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);
Related
How can I use foreach multiple times?
<?php
$query = $db->query('SELECT tbl_stok.id_stok,
tbl_stok.id_provinsi,
tbl_stok.id_kabupaten,
tbl_stok.tanggal,
tbl_stok.mie_instan,
tbl_stok.beras,
tbl_stok.telur
FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
');
$query->fetchAll;
?>
I want to use the first foreach to show the data tables:
<?php foreach($query as $row){
echo $row['beras'];
}?>
Then I want to use the second foreach for chart:
<?php foreach($query as $row){
echo $row['telur'];
}?>
However, this foreach works only once.
You can do this:
1) save your data to an array.
foreach($query as $row){
$data[]= $row;
}
2) use your array in every loop you want as many time you want
foreach($data as $row){
echo $row['beras'];
}
foreach($data as $row){
echo $row['telur'];
}
Use foreach only once and store all values you need, like this:
<?php
$beras_array = array();
$telur_array = array();
foreach($query as $row){
$beras_array[] = $row['beras'];
$telur_array[] = $row['telur'];
}
//you can use `for` explained later instead of two `foreach`
foreach($beras_array as $b){
echo $b;
}
foreach($telur_array as $t){
echo $t;
}
//With this method you can also use only one for instead of two foreach
$limit = count($beras_array);
for($i=0; $i<$limit; $i++){
echo $beras_array[$i];
echo $telur_array[$i];
}
?>
I hope it helps
I have a MySQL database that has a column with a bunch of descriptions. I want those in a PHP array imitating this:
$Description[0] = "Here's a description";
$Description[1] = "Here's another description";
$Description[2] = "Wow, many descriptions";
$Description[3] = "Another one";
$Description[4] = "They just keep going";
...etc
I'm struggling with the while loop logic to make this happen though. Help!
$result = mysql_query(...);
$Description = array();
while ($row = mysql_fetch_array($result)) {
array_push($Description, $row["columnyouwant"]);
}
$Description = array();
$result = mysql_query(......);
while ($row = mysql_fetch_array($result))
{
$Description[] = $row;
}
// echo print_r($Description);
hi very simple...
foreach ($Description as $value) {
echo $value;
}
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.
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
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 */
?>
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.
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..
}
?>
Hi all Im trying to query a database and store the results ($searchResults[]) as an array :
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings
WHERE location = '$locationListResults' AND industry = '$selected'");
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
}
}
mysqli_close($con);
}
?>
the problem im getting is when I try to echo the result:
<?php
echo $searchResults[0];
?>
its only bringing back 1 result not displaying all the results in the arrray as i want it to.
Could anybody please point out what it is im doing wrong.
Any help would be greatly appreciated
Do like this
<?php
print_r($searchResults); // Prints all array elements
?>
Alternatively, you can make use of a for loop to echo all elements too..
foreach($searchResults as $k=>$v)
{
echo $v;
echo "<br>";
}
Your code puts your data into 1D array. You probably want sth else so instead of this:
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
do this:
$tmp = array();
$tmp['industry'] = $row['industry'];
$tmp['location'] = $row['location'];
$tmp['title'] = $row['title'];
$tmp['description'] = $row['description'];
$searchResults[] = $tmp;
or just this (thanks to Barmar):
$searchResults[] = $row;
This way you store your data as 2D array. So every row you obtain remains in one subarray.
To print the row (which is now in 2D array) iterate over subarrayw:
foreach($one_of_searchResult_rows as $k => $v)
{
// do whatever you need with $k and $v
}
I think you want a 2d array. Try this code snippet :
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
array_push($searchResults,$row);
}
This should push each row as an associative array in every cell of your final searchResuts array. You could then access the values like:
echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result
Lets make it simple :
$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);
Reference : mysqli_fetch_all
I have an array.
$select_crm=mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
$select_array=array($select_crm);
if(mysql_num_rows($select_crm)>0)
{
foreach($select_array as $v)
{
$fetch_crm=mysql_fetch_array($v);
echo $fetch_crm['party_name'];
echo $fetch_crm['partyid'];``
}
}
But it can't works properly. $select_crm have two rows but it print only one.
$select_array is an array with just one element: the query result resource. Therefore the foreach loop will only ever run once, printing only the first item.
Your loop should look like every single tutorial out there:
while($fetch_crm = mysql_fetch_assoc($v)) { ... }
Note fetch_assoc, not fetch_array. It is pointless to call fetch_array if you don't intend to use the numeric indices.
As far as I'm concerned, you have to do this:
$select_crm=mysql_query("select * from party_details where subcaseid='{$under_row['partyid']}'");
if(mysql_num_rows($select_crm)>0)
{
while ($select_array = mysql_fetch_assoc($select_crm))
{
echo $select_array['party_name'];
echo $select_array['partyid'];
}
}
$select_crm="select * from party_details where subcaseid='{$under_row[partyid]}'";
$crm = mysql_query($select_crm) or die(mysql_error());
$row_crm = mysql_fetch_assoc($crm);
$totalRows_crm = mysql_num_rows($crm);
if($totalRows_crm > 0) {
do {
/*foreach ($row_crm as $field) {
echo $field;
}*/
echo $row_crm['party_name'];
echo $row_crm['partyid'];
} while ($row_crm = mysql_fetch_assoc($crm));
}
do not use foreach , you should use in this way ,
$select_crm= mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
while($result = $db->fetchByAssoc($select_crm))
{
echo $result ['party_name'];
echo $result ['partyid'];
}
try this:
<?php
$select_crm =
mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
while($select_array = mysql_fetch_assoc($select_crm))
{
echo $select_array['party_name'];
echo $select_array['partyid'];
}
?>
hope it will help.
happy coding!
try this
$result = mysql_query("your select query");
while($row = mysql_fetch_assoc($result)){
echo $row['columnNam1'];
echo $row['ColumnName2'];
}
Use this:
$select_crm=mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
while($row=mysql_fetch_assoc($select_crm)) {
echo $row['party_name'];
echo $row['party_id'];
}
Your code is iterating over an array which only 2 lines above you explicitly created to have exactly one element ;-)
You have misplaced the use of mysql_fetch_assoc. Check out the manual page and the sample code there for your solution. (and while you are there, notice the big red DEPRECATED notice; read on!).