I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.
Related
Im not sure if a similar question has been asked before, but here goes anyway. (I did do a search and found nothing relating to my question).
I am developing a website in which videos are played using the HTML5 video player. I have a connection to my database, a "watch" page that pulls all the correct data using a variable linked to the id (watch.php?v=1). I would like to have an index page where the most recent videos are pulled. They are ordered by the column "id" and everything works when I try and pull one result from the query. How would I go about getting multiple values? Here is my php code (server details hidden):
<?php
$mysqli = new mysqli("HIDDEN", "HIDDEN", "HIDDEN", "HIDDEN");
$sql = "
SELECT id, title, imgsrc, description
FROM videos
ORDER BY id DESC
LIMIT 2
";
$result = $mysqli->query($sql);
$video = mysqli_fetch_array($result, MYSQLI_ASSOC);
mysqli_close($mysqli);
?>
And here is my HTML code for the table.
<table>
<tr>
<td><h2><? echo $video['title']; ?></h2></td>
</tr>
</table>
That isn't the full code, but once I know the procedure I can apply it where needed!
I'm quite new to php and mysql, I can connect to databases but that's about it so a full walkthrough about what does what would be great!
Many Thanks,
James Wassall
You can iterate in for or while loop by calling mysqli_fetch_array($result, MYSQLI_ASSOC):
<table>
<?php
$mysqli = new mysqli("HIDDEN", "HIDDEN", "HIDDEN", "HIDDEN");
$sql = "
SELECT id, title, imgsrc, description
FROM videos
ORDER BY id DESC
LIMIT 2
";
$result = $mysqli->query($sql);
while($video = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?>
<tr>
<td><h2><? echo $video['title']; ?></h2></td>
</tr>
<?php
}
mysqli_close($mysqli);
?>
</table>
Note that you should consider checking error statements, null controls etc.
try this
while($video = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<tr>
<td><h2><?php echo $video['title']; ?></h2></td>
</tr>
<?php
}
?>
Each time you call mysqli_fetch_array, only one row is fetched.
You need to do something like
while ($video = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// output $video['title']
}
(according to: http://www.php.net/manual/en/mysqli-result.fetch-array.php)
Try this,
<table>
<?php while($row = $result->fetch_array(MYSQLI_ASSOC)){ ?>
<tr>
<td><h2><? echo $row['title']; ?></h2></td>
<td><h2><? echo $row['description']; ?></h2></td>
</tr>
<?php } ?>
</table>
I want to construct an html table based on the returned results from the database. Assuming I have a table called constraints in my database and a column called riskName and it has these values: Security, Financial, Legal and Technical as shown in the image below. How do i loop through my database and come up with this table. I have tried different approach but no has worked. Here is my code so far:
<?php
error_reporting(0);
$optioner = 12;
$getObs = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
$result = $riski->fetch(PDO::FETCH_ASSOC);
while($getObs->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>".($result['riskName'])."<td><tr>";
//...other code
}
?>
</tbody>
<?php };
?>
I'm not sure if this will give you the exact table you're looking for, but it should at least put you on the right lines. Also, you weren't keeping your variables the same and notice how $result is set in the while loop
$optioner = 12;
$riski = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
?>
<form>
<table>
<tr> <th>i</th> <th>Importance</th> <th>How Much More?</th> <tr>
<?php
while($result = $riski->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
echo '<td>'. $result['riskName']).'<td>';
echo '<td>';
for ($i=1;$i<10;$i++){
//radio buttons go here
}
echo'<tr>';
//...other code
}
?>
Sorry I couldn't help more.
Hope this works for you.
I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.
My professor helped me create this function:
<?php
include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']
);
}
}
//print_r($new_row);
?>
the print_r($new_row); is only there to make sure it works and it does, it prints out the array when activated.
He then guided me to create the table like this:
<body>
<table id="demo">
<?php foreach($new_row as $row):?>
<tr>
<td><?=$row['year'];?></td>
<td><?=$row['country'];?></td>
</tr>
<?php endforeach;?>
</table>
<script type="text/javascript">
$(document).ready(function() {
// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...
});
});
</script>
</body>
What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.
I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.
You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:
<?php foreach($new_row as $country => $rows): ?>
<?php foreach($rows as $row): ?>
<tr>
<td><?=$country;?></td>
<td><?=$row['Year'];?></td>
<td><?=$row['Value'];?></td>
</tr>
<?php endforeach;?>
<?php endforeach;?>
Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here: http://php.net/manual/en/control-structures.alternative-syntax.php
If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:
<?php foreach($new_row as $country => $rows):
$sum = 0;
foreach($rows as $row):
$sum += $row['Value'];
endforeach;
?>
<tr>
<td><?=$country;?></td>
<td><?=$sum;?></td>
</tr>
<?php endforeach;?>
You should be using a single JOINed query to do this stuff, but you may not have gotten that in class yet. Since it's homework, I won't give you the flat-out answer, but here's the pseudo-code:
$countries = SELECT DISTINCT Country FROM YourTable;
while($country_row = fetch_row($countries)) {
echo $country_row['Country'];
echo <table>;
$status = SELECT Year, Value FROM YourTable WHERE Country=$country_row['Country'];
while($stats_row = fetch_row($status) {
echo <tr><td>$stats_row['Year']</td><td>$stats_row['Value']}</td>
}
echo </table>
}
I'm trying to display information from a table in my database in a loop, but for certain information, I'm referencing other tables. When I try to get data from other tables, any data following will disappear. here is the code I am using:
`
//Below is the SQL query
$listing = mysql_query("SELECT * FROM Musicians");
//This is displaying the results of the SQL query
while($row = mysql_fetch_array($listing))
{
?>
...html here...
<? echo $row['name']; ?>
<? echo $row['Town']; ?>
<?
$CountyRef = $row['CountyId'];
$county = mysql_query("SELECT * FROM County WHERE CouInt='$CountyRef'");
while($row = mysql_fetch_array($county))
{
echo $row['CouName'];
}
?>
<?php echo $row['instrument']; ?>
<?php echo $row['style']; ?>`
My problem is that everything after the second while loop is not displaying. Anyone have any suggestions?
Thanks
Second loop should say $row2. $row is being overwritten. Both variables should be named different from each other.
You can acomplish that with a one single query:
SELECT *,
(SELECT CouName FROM County WHERE CouInt=mus.CountyId) as Country
FROM Musicians mus;
You final code should looks like:
<?php
$listing = mysql_query("SELECT *,
(SELECT CouName FROM County WHERE CouInt=mus.CountyId) as Country
FROM Musicians mus;");
//This is displaying the results of the SQL query
while($row = mysql_fetch_assoc($listing))
{
echo $row['name'];
echo $row['Town'];
echo $row['Country']; //Thats all folks xD
echo $row['instrument'];
echo $row['style'];
} ?>
Saludos ;)
And that?:
while($row2 = mysql_fetch_array($county)) {
echo $row2['CouName'];
}
I cannot seem to get foreach to work. Maybe I do not understand it correctly.
Here is my code:
$statement = "SELECT * FROM categories ORDER BY name ASC";
$query = mysql_query($statement)
...
...
$cals = array("sports","general","other","clubs");
foreach ($cals as $value)
{
/* echo "<h3>".$value."</h3>";
*/ echo "<table width='100%'>";
while ($array = mysql_fetch_array($query))
{
if ($array['calendar'] == $value)
{?>
<tr>
<td><?php echo $array['name']; ?></td>
<td><a onclick="update_form('<?php echo $array['name']; ?>', '<?php echo $array['calendar']; ?>')" href="#">Edit</a></td>
</tr>
<?php }
}
echo "</table><br />Value: $value";
}
The goal of this is to have the foreach change the if statement. I had planned for the if statement to say: if ($array['calendar'] == "sports") the first time, if ($array['calendar'] == "general") the second time, and so on. However, it shows all of the tables (in the source code), but no table rows are created after the first for each array value. For example, I correctly see the sports table, but I do not see any table rows for general, other, or clubs. There are records in that database that should appear in each of those. Could it be a problem with the while and if statements? If I manually set the $value in the if statement to one of the values in the array, it shows the correct records.
What am I missing?
Sample Data:
in the MySQL database -
categories table.
fields:
id
name
num_events
calendar
calendar_url
All of these fields except the calendar field has dummy data in it.
Currently, I have 5 records in there. Each one has a different calendar value. One is sports, one is clubs, and one is general. Depending on what value I place first in the array, it only shows that one table, of all of the values with whatever the first value in the array is.
Here is the source code from the resulting page:
<table width='100%'><tr>
<td>test4</td>
<td><a onclick="update_form('test4', 'sports')" href="#">Edit</a></td>
</tr>
<tr>
<td>test5</td>
<td><a onclick="update_form('test5', 'sports')" href="#">Edit</a></td>
</tr>
</table><br />Value: sports<table width='100%'></table><br />Value: general<table width='100%'></table><br />Value: other<table width='100%'></table><br />Value: clubs
As jcubic and timdev pointed out, there are a couple problems with the code as written. However, the algorithm you're trying to use is very inefficient because it loops over the entire result set for every calendar type. Instead, you can use a multi-column sort in SQL to do it in one pass:
$query = "SELECT * FROM categories ORDER BY calendar, name";
$results = mysql_query($results)
...
...
$last_cal = '';
while ($array = mysql_fetch_assoc($query))
{
if (!$last_cal) {
echo '<table>';
}
else if ($array['calendar'] != $last_cal) {
echo '</table>';
echo '<table>';
}
?>
....HTML for table row...
<?php
$last_cal = $array['calendar'];
}
First, just a point of style. You might consider renaming your variable $query to something like $results. It's holding the result of a query, not a query itself.
The problem is that you're not resetting $results. After the first table, you've iterated all the way through the array. When you get to the end, and there are no more rows to iterate over, mysql_fetch_assoc() returns false.
So try this:
foreach ($cals as $value)
{
while ($array = mysql_fetch_array($query))
{
if ($array['calendar'] == $value)
{
?>
<tr>
<td><?php echo $array['name']; ?></td>
<td><a onclick="update_form('<?php echo $array['name']; ?>', '<?php echo $array['calendar']; ?>')" href="#">Edit</a></td>
</tr>
<?php
}
}
echo "</table><br />Value: $value";
mysql_data_seek($query,0); // <=== Set the resultsets internal pointer back to zero (the first record).
}
The important bit is the mysql_data_seek() on the second to last line.
You could also stick that mysql_data_seek() right before the while() line, if you prefer. You just need to make sure that for each iteration of the foreach loop, the array pointer is reset before you hit while().
EDIT: s/reset/mysql_data_seek/
Try this instead...
$result = mysql_query($query);
while ($array = mysql_fetch_array($result)) {
...
}
mysql_fetch_array return array indexed by integer if you want asoc array change
while ($array = mysql_fetch_array($query))
to this
while ($array = mysql_fetch_assoc($query))