I am having this weird problem.
There are seven admins: darth, jane, luke, najin, root, sam and sydney.
CODE:
<table>
<tr>
<th style="text-align: left; width: 200px;">Username</th>
<th colspan="2" style="text-align: left;">Action</th>
</tr>
<?php
$sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
$result = mysqli_query($connection, $sql);
$admin = mysqli_fetch_assoc($result);
while($admin = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo ($admin["Admin_Username"]); ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
}
?>
</table>
If I use ASC order, the first admin, darth is not displayed in the loop and if I use DESC order, the last admin, sydney doesn't show up.
What could be the problem here?
Get rid of the first $admin = line.
Your loop will fetch all of them; you don't need to fetch the first one separately (and if fact by doing so are skipping it, because your loop immediately fetches the second before the first one could be written out).
remove this line
$admin = mysqli_fetch_assoc($result);//You already fetching the first result here
You have a redundant call to $admin = mysqli_fetch_assoc($result); before the while loop which will cause you to skip the first row of the result. Just remove it and you should be fine.
<?php
$sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
$result = mysqli_query($connection, $sql);
while($admin = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo ($admin["Admin_Username"]); ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
}
?>
$admin = mysqli_fetch_assoc($result);
This must be in while loop So you can descard/remove old value above while
Related
for a project in HTML,CSS,PHP and JS I have to print the cells of a table according to the elements of a database. For example, if a cell is property of user1#test.com I want that the cell is blue, because in the database the colour for the user1 is blue. I have associated with success the user with the colour in the database, but I'm not able to scan every cells of the table.
In fact, my code is able to colour in blue just one cell of a single user, even if the user1 has more than one prenotation. This is my code:
$result = mysqli_query($db, "SELECT * FROM users");
$users=$result->fetch_assoc();
foreach ($users as $result){
$result = mysqli_query($db, "SELECT * FROM prenotations WHERE username='user1#test.com'");
$info_prenotations=$result-> fetch_assoc();
$result = mysqli_query($db, "SELECT * FROM colors WHERE username='user1#test.com'");
$info_colour=$result-> fetch_assoc();
$result = mysqli_query($db, "SELECT username from prenotations where username='user1#test.com'");
$info_username=$result->fetch_assoc();
}
And this is the cose for the table:
<table border="0" summary="Week">
<tr>
<th></th>
<th>Mon</th>
<th>Thur</th>
<th>Wed</th>
<th>Tues</th>
<th>Fri</th>
</tr>
<?php for ($i=1; $i<=11; $i++) { ?>
<tr>
<th>Slot <?php echo $i; ?></th>
<?php for ($j=1; $j<=5; $j++) { ?>
<td style="<?php if (intval($info_prenotations["slot"]) == $i && intval($info_prenotations["day"]) == $j) { echo "background-color: ".$info_colour["colour"].";"; } ?>"></td>
<?php } ?>
</tr>
<?php } ?>
</table>
Now I want to use the foreach loop in a way that I can scan the entire table to print the different cells for the different users. I suppose that my error is in the foeach loop, which I don't understand very well. Someone can help me, please?
I really can't figure out what I'm doing wrong here. I'm doing a query to check whether there are records in a DB table called 'newCards'.
With $count I check how many results it's returning: it shows me '1'. But the while loop isn't returning ANY thing. The only things I'm seeing are the <th>'s at the top of the table, but no table records are present, while $count is giving '1' as a result. Which is true, cause there is actually 1 record present in DB.
How can I fix this?
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if(empty($query->fetch())){
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
$query->fetch() already fetches a record. So next call to fetch() fetches next record or nothing if there're no records. In your case with one record second fetch() fetches nothing, so while never starts.
You can change your code to:
if($count){?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
// show row
}?>
</table>
} else {
// echo that no rows found
}
I think fetch in first if is executed so that is why second returns empty,
try to assign it to var before conditions or check wit $cont var
I believe you want to return an array indexed by column names with
->fetch(PDO::FETCH_ASSOC)
More information can be found here http://php.net/manual/en/pdostatement.fetch.php
Because fetch() fetches the first row, even when checking in empty(), it will try to fetch the next row when you use while($result = $query->fetch()){. You can either check the value from $count (like shown by u_mulder), but you should beware of the note in the manual for rowCount() (emphasis mine)
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications.
You can use a do..while structure and check if the fetch was successful or not instead. If you change out if(empty($query->fetch())){ with if (!$row = $query->fetch()) {, you check if there was a row fetched or not (as fetch() returns null on an empty result). Then $row is ready to use, and you can use it before the first loop takes place.
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if (!$row = $query->fetch()) {
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
do {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
} while ($result = $query->fetch());
?>
</table>
<?php
}
PHP.net on PDOStatement::rowCount()
PHP.net on do..while
I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!
I executed this code in localhost but it kept looping the table infinitely. How do I fix this? Is there something I should add? The looping never stops until I click the x button to stop loading the page.
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$query=("SELECT * FROM songs ORDER BY songid DESC");
$result = mysql_query($query) or die(mysql_error());
?>
<html>
<head>
<title>View</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Song ID</td>
<td>Title</td>
<td>Artist</td>
<td>Genre</td>
<td>Language</td>
<td>Lyrics</td>
<td>Updated by</td>
</tr>
<?php
$counter == 1;
$res = mysql_fetch_array($result);
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
do {
echo "<tr>";
echo "<td>".$res['songid']."</td>";
echo "<td>".$res['title']."</td>";
echo "<td>".$res['artist']."</td>";
echo "<td>".$res['genre']."</td>";
echo "<td>".$res['language']."</td>";
echo "<td>".$res['lyrics']."</td>";
echo "<td>".$res['update']."</td>";
echo "<td>Edit | Delete</td>";
} while($res)
?>
</table>
You are missing $res = mysql_fetch_array($result); at the end of the loop. Currently, the while statements checks if $res is (still) truthy, but it never changes, so it will always evaluate to TRUE (and so, the loop will always continue to run).
I was just about to write the same thing as Daan Meijer. res never changes and so its always true for the while-statement. I just want to add that mysql_fetch_assoc($result) works a littlebit faster than mysql_fetch_array($result). So if you have a big database, mysql_fetch_assoc($result) is the better choice.
I am new to PHP/MySQL to please bear with me. I am trying to have PHP write a table which returns a list of records from a join table. The SQL statement works perfectly when I run the query but I do not know how to write the function properly.
SQL statement which works:
SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets
ON shares.asset_ID = assets.asset_ID)
INNER JOIN members
ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID"
My functions:
function get_shares_by_member($member_ID) {
global $db;
$query = "SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets
ON shares.asset_ID = assets.asset_ID)
INNER JOIN members
ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID";
$share_result = $db->query($query);
$share_result = $share_result->fetch();
return $share_result;
}
function get_shares() {
global $db;
$query = "SELECT * FROM shares";
$share = $db->query($query);
$shares_table = $share->fetch();
return $share;
}
My action:
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'list_shares';
}
if ($action == 'list_shares') {
if (!isset($member_ID)) {
$member_ID = 0;
}
$shares = get_shares_by_member($member_ID);
$share = get_shares();
}
Here is my table:
<table>
<tr>
<th>Nick Name</th>
<th>Asset Description</th>
<th>Asset Cost</th>
<th class="right">% Ownership<th>
<th> </th>
</tr>
<?php foreach ($shares_table as $share) : ?>
<tr>
<td><?php echo $share['nick_name']; ?></td>
<td><?php echo $share['asset_desc']; ?></td>
<td><?php echo $share['asset_cost']; ?></td>
<td class="right"><?php echo $share['percent_owner']; ?></td>
<td> </td>
</tr>
<?php endforeach; ?>
</table>
I know this is a lot to ask but I've been struggling with this for the past 3 days. Any help will be much appreciated! If anyone needs help with AD/Exchange, I'd be happy to share my knowledge in that area!
Thanks!!
From what I can see on here, this will produce a blank table with however many rows are returned for a number of reasons:
None of the columns returned by the get_shares_by_member function are share_ID or asset_ID, so those columns won't be filled in.
You are referencing percent_owner from $shares which, assuming is an array as you are using it in a 'foreach' loop, will need an index to reference it, or it should otherwise be $share['percent_owner']
The percent_owner field will be put in the 'asset cost' column at present as there is no blank cell produced to move it to the '% ownership' column where it would seem logical to have it.
Based on what you have posted so far, the following should suit your needs:
<table>
<tr>
<th>Nick Name</th>
<th>Asset Description</th>
<th>Asset Cost</th>
<th class="right">% Ownership<th>
<th> </th>
</tr>
<?php foreach ($shares as $share) : ?>
<tr>
<td><?php echo $share['nick_name']; ?></td>
<td><?php echo $share['asset_desc']; ?></td>
<td><?php echo $share['asset_cost']; ?></td>
<td class="right"><?php echo $shares['percent_owner']; ?></td>
<td> </td>
</tr>
<?php endforeach; ?>
</table>
I would recommend changing either the $share variable in the foreach, or the $share which is being set by get_shares(). Personally speaking, I would change the latter from
$share = get_shares();
to something like:
$shares_table = get_shares();
as it is essentially containing all of the information from the shares table, assuming the database abstraction layer function fetch() returns all results.
There could also be an issue when you are doing:
$share = $db->query($query);
$share = $share->fetch();
Going from different database abstraction layers I have seen, I would expect fetch() to be done as (using your variables)
$share = $db->fetch();
If the fetch() is requiring a result to be passed into it, then I would expect the code to look similar to:
$share_result = $db->query($query);
$share = $db->fetch($share_result);
a few points:
are you sure your query does not return any errors? If there are
errors, that might cause fetch() to fail
what DB class are you using? I would suggest that you please check
that there is a fetch() function and what parameters does it accept? For example, the fetch() may be invoked like $share_result->fetch() or $db->fetch() or $db->fetch($share_result) etc.
I might be wrong but it seems that the fetch() might be always
returning the first row from the resultset. Perhaps you might need
to do fetch() in a loop for reading all results
You may as well try using the default PHP functions. Here is a code snippet that explains how you may rewrite your functions using PHP's default mysql() library:
mysql_connect('your host', 'your user', 'your password'); function get_shares_by_member($member_ID) {
$output = Array();
$query = "SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets ON shares.asset_ID = assets.asset_ID)
INNER JOIN members ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID";
$share_result = mysql_query($query);
while ($row = mysql_fetch_assoc($share_result)) {
$output[] = $row;
}
return $output;
}
function get_shares() {
$output = Array();
$query = "SELECT * FROM shares";
$share = mysql_query($query);
while ($row = mysql_fetch_assoc($share)) {
$output[] = $row;
}
return $output;
}
Hope the above helps. Please feel free to let me know if there is anything that is not clear.