I am having a bit of an issue if there is no categories I need to echo no categories if there is I need it to echo There are categories. it shows if there is categories, but don't show if there is not.
<tr>
<?php
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM discussion_categories");
$stmt->execute();
$result = $stmt->get_result();
while (($row = mysqli_fetch_assoc($result)) == true) {
$CategoryID = $row['CategoryID'];
$Name = $row['Name'];
$Description = $row['Description'];
$Photo = $row['Photo'];
if(!empty($CategoryID['CategoryID'])){
echo "<td>No categories</td>";
} else {
echo "<td colspan='4'><img class='profile-photo' src='" . ROOT_URI . "/uploads/" . $Photo . "'></td>";
echo "<td colspan='4'><a href='discussions.php?view={$CategoryID}'>{$Name}</a></td>";
echo "<td><a href='managecategories.php?delete={$CategoryID}'>delete</a></td>";
}
}
?>
</tr>
That's an easy to solve problem.
If there is no category the while loop gets never executed because there are no rows in your db result.
Try and check the row amount first:
if (mysqli_num_rows($result) == 0) {
//there are no categories
echo('no categories');
} else {
//there are categories
echo('there are categories');
//in case you want to loop through your categories now
while (($row = mysqli_fetch_assoc($result)) == true) {
$CategoryID = $row['CategoryID'];
echo($CategoryID);
//your code
}
}
This should help you!
If there are no categories, then this condition:
while (($row = mysqli_fetch_assoc($result)) == true)
Which is a long-winded way of writing this:
while ( $row = mysqli_fetch_assoc($result) )
Will never be true, so you'll enter the loop zero times - there will never be a "truthy" value for $row.
If we write out your code as pseudo-code, we get:
inspect each result
if the result has a non-empty CategoryID, echo "No categories"
if the result has an empty CategoryID, echo "There are categories"
end of loop
The two if checks are the wrong way around, but more importantly they are inside the loop.
What you probably meant was something like this:
set found_results flag to false
inspect each result
if the result has a non-empty CategoryID, set found_results flag to true
perform other operations on the result, or use "break;" to end the loop early
end of loop
if found_results flag is true, echo "There are categories"
if found_results flag is false, echo "No categories"
I'll leave it to you to translate that back into PHP. :)
Of course, if you really only need to know if there are results or not, you can write this much neater by:
counting the rows returned using mysqli_num_rows
using SELECT COUNT(*) in your SQL instead of SELECT *, possibly also with a WHERE CategoryId IS NOT NULL clause
if you have no results, then it wont even go in the while loop, so your conditional statement is redundant (which is why you get no output).
Youre better off, as mentioned in some of the comments to check for the results before you try to do anything with them.
if($result->num_rows > 0) {
// you now know there are results
while ($row = mysqli_fetch_assoc($result)) {
// do your business in here as you would have, but you dont need to worry about nothing to process
}
} else {
// do something in here to send back a null result, or whatever you like
}
while (($row = mysqli_fetch_assoc($result)) == true)
According to the above part of the code. It will only go inside the while loop if there is any data returned or fetched from the database else if no data has been fetched it will not enter the loop.
If there is no categories then it will go out of the loop and so this echo "<td>No categories</td>";will never be shown.
Also since you have put an echo saying 'No Categories', I assume that it means you want to echo an output if there is no category. But your if condition is wrong since, if u want to check if some variable is empty you need to do as below
if(empty($CategoryID['CategoryID'])){
echo "<td>No categories</td>";
} else {
echo "<td colspan='4'><img class='profile-photo' src='" . ROOT_URI . "/uploads/" . $Photo . "'></td>";
echo "<td colspan='4'><a href='discussions.php?view={$CategoryID}'>{$Name}</a></td>";
echo "<td><a href='managecategories.php?delete={$CategoryID}'>delete</a></td>";
}
where if(empty()) will be true if it is empty and if(!empty()) will be true if it is not empty.
If I understand it correctly, you are should use empty() not !empty().
The code run like:
if(!empty($CategoryID['CategoryID'])){ //if cat is not empty it says no cat
//notice the ! in front of empty tag
echo "<td>No categories</td>";
} else {
echo "<td>There are categories</td>";
}
according to your code, if the categories are empty, it will display there are categories.
By calling the While loop you are saying that, if the query return at least one category in the result.
The loop is thus confused when there is no category. Try replacing the empty() with count of CategoryID greater than zero and see what happens.
if > 0
exist
else
does not exist
Related
Can someone please point out what I'm sure is a stupidly obvious error in my code? The string "string" in my while loop is displaying the correct amount of times but not the results in row[0].
if (!isset($_GET['city']) & !isset($_GET['county'])) {
$getResults = "SELECT DISTINCT region FROM `locations` WHERE country = 'England'";
echo "No region or county set";
if ($result = $mysqli->query($getResults)) {
echo "Found results";
while ($row = $result->fetch_assoc()) {
echo "string";
echo $row[0];
}
}
}
To see the contents of the $row array dump it out like so var_dump($row).
I'm guessing you just need echo $row['region'] rather than $row[0]
You are using fetch_assoc() but you try to access the row using a index numbers.
Use fetch_row() instead.
I intend for the following code to display an 'h2' tag and text (displayed in the else statement at the bottom of the code) if there are no recorders that meet the SQL statement for a MySQL table property 'isVisible' == 1.
I decided to test to see if the query returned a 'null' result, this must be where I have a flaw in my logic. The result of my query must still be returning a value other than null even though none of the records match the "WHERE isVisible = 1" part of the SQL statement.
I only have one record in the DB hard coded to '0'. When the 'isVisible' property is returned to a value of '1' then the code executes properly. The exception is the only thing causing me trouble. I don't usually work with PHP much, so I am sure I probably just testing the wrong condition at the first if statement a few lines down.
Thanks for your time and help.
<?php
// Generate SQL Statements
$sql_position = "SELECT * FROM tbl_experience
WHERE isVisible = 1
ORDER BY 'displayPosition'";
// Run Query
$result = mysql_query($sql_position);
// Iteration Variable
$i = 0;
if ($result != null) {
// List all of the experiences as a timeline
while($row = mysql_fetch_array($result)) {
// Build a div to contain the experience properties
echo "<div id='experienceContainer_" . $row['displayPosition'] . "' class='experienceContainer";
if (i % 2) {
// The row should be displayed with 'Even' class attributes
echo " Even";
} else {
// The row should be displayed with 'Odd' class attributes
echo " Odd";
}
// Finish the opening <div> tag
echo "'>";
// Display the attributes of the experience
// Experience Type
echo "<div id='type_" . $row['displayPosition'] . "' class='experienceType'>";
switch ($row['type']) {
case 0:
echo "Undefined";
break;
case 1:
echo "Work";
break;
case 2:
echo "Achievement";
break;
case 3:
echo "Award";
break;
}
echo "</div>";
// Experience Title
echo "<div id='title_" . $row['displayPosition'] . "' class='experienceTitle'>";
echo $row['title'];
echo "</div>";
// Experience Description
echo "<div id='description_" . $row['displayPosition'] . "' class='experienceDescription'>";
echo $row['description'];
echo "</div>";
// Close the 'experienceContainer' div
echo "</div><!-- end of experienceContainer_" . $row['displayPosition'] . " -->";
}
} else {
// There are no visible records
echo "<h2>No entries for \"Experience\" can be found</h2>";
}
you need to use mysql_num_rows
if (mysql_num_rows($result) > 0) {
this if condition will guarantee that you will be routed to the else condition when there is no rows to display.
All I need to do is echo array pocket $row[0].
while ($row = mysqli_result::fetch_array($result)) {
echo '<br>' . $row[1];
}
echo $row[0];
I have googled, but results haven't helped. I know I'm missing something stupid, but I'd appreciate the help!
I'm trying to echo the database column, 'ID'. An example of the data I want to echo would be '3'.
Copy $row[0] as you go.
$lastZero = "";
while ($row = mysqli_result::fetch_array($result)) {
echo '<br>' . $row[1];
$lastZero = $row[0];
}
echo $lastZero;
For debugging the whole row, write this:
var_dump($row)
To output the column ID, write this:
while ($row = mysqli_result::fetch_array($result)) {
var_dump($row); // This will output all values for each row as they're looped through
echo '<br>' . $row['ID'];
}
var_dump($row); // dumps the last row of the returned results, or false if no rows.
echo $row['ID']; // echos the ID of the last row. However if there are no rows, this will not work.
Be aware, as #Daedalus pointed out, $row is an array, so the var_dump line is really just for debugging. Because an array has multiple values, PHP doesn't know how you want to display it. You'll need to program how each element of $row is displayed.
I'm trying to determine the right syntax from what I'm trying to do with MySQL. I'm basically saying that if a value in a certain column of a row of a table is equal to some session variables, I want to echo out info.
I have a table with subject, description and user. User is set by taking the current user's first name and last name and inserting it into the table under user. This is done by the following code:
$sql="INSERT INTO tbl_name (subject, description, user)
VALUES
('$_POST[subject]','$_POST[description]','$_SESSION[firstname] $_SESSION[lastname]')";
Then once I'm calling this data back out, I want to basically allow the user to delete content that they submitted themselves. The first step for me is to be able to display it in the table. I believe this is just syntax error, but I've confused myself now with how things are set up:
$sql = "SELECT * FROM tbl_name ORDER BY subject, description
LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME EXAMPLES:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if('$field->user' == '$_SESSION[firstname] $_SESSION[lastname]'){
echo '<td>You can delete this</td>';
}
}
I figured the $field->user would equal $_SESSION[firstname] $_SESSION[lastname] because that's how it was initially submitted to the table (without the '.' for concatenation).
Any help would be appreciated. Thanks!
EDIT
Here's the result of my table output code. The results are actually being display with $cell instead of from within the for loop I believe. I've added the if statement in after the but it doesn't seem to recognize echo "<td>".$field->user."</td>"; which makes me think that that is where the problem lies. What I would like to do is be able to add the if statement in a immediately after `echo {$field->user}"; to keep the code clean. I think I've confused myself thoroughly:
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME JOBS:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if($field->user == $_SESSION[firstname]." ".$_SESSION[lastname]){
echo '<td>You can delete this</td>';
}
else{
echo "<td>".$field->user."</td>";
echo "<td>".$_SESSION[firstname]." ".$_SESSION[lastname]."</td>";
}
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no jobs!';
}
I re-wrote the code in a way that was a little bit easier for me to understand (though maybe not the shortest way to do it):
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
It ended up working this way. If there's way to do this shorter then feel free to post it here otherwise thanks for the help!
Thank you for reading my question.
I am trying to make a site where information from a database is displayed onto a webpage. The end result will look like this, but for a different game.
Here is a plain HTML page of what I want it to look like.
So far I know that my connection to the database works. When I run:
mysql_select_db("DATABASE", $con);
$result = mysql_query("SELECT * FROM DATABASE");
while($row = mysql_fetch_array($result)) {
echo $row['Title'] . " " . $row['Type'];
echo "<br />";
}
It returns the Title and Type.
What I want to do is run an If/Else statement that runs a different that block of code depending on the card type.
while($row = mysql_fetch_array($result)) {
if ($row['Title'] == 'Hero') {
echo "<div>";
}
}
I tried this based on the tutorials at w3schools.com but it doesn't work.
Do any of you have any ideas for what I should do?
EDIT:
Here is what I tried running:
while($row = mysql_fetch_assoc($result)) {
if ($row['Title'] == 'Hero') {
echo $row['Title'] . " Hero.<br>";
} else {
echo $row['Title'] . " Who cares.<br>";
}
}
Here is the output (Gimli should show up as a Hero):
For Gondor! Who cares.<br>
Bilbo Baggins Who cares.<br>
Ungoliant's Spwan Who cares.<br>
Gimli Who cares.
EDIT 2: Thank you Phil for spotting the error, I now get the result I wanted using Mikushi's method. Thank you all so much.
The fetching of your mysql result seems wrong, should be like this:
while($row = mysql_fetch_assoc($result)) {
if ($row['Title'] == 'Hero') {
echo ""; }
}
mysql_fetch_array fetch the result as an indexed array (1=> data, 2=> thing) , which explains why $row['Title'] doesn't work.
The difference:
http://ca2.php.net/mysql_fetch_array
http://ca2.php.net/mysql_fetch_assoc
Please, always refer to the documentation, it's very well done and a better source than w3cschools.
Maybe it's one of those all too obvious things but...
Shouldn't it be
if ($row['Type'] == 'Hero') // "Type", not "Title"