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.
Related
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
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!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to iterate by row through a mysql query in php
After:
$result = mysql_query($query) or die("Error: Cant query database");
All Im trying to do is iterate through the result one by one and display the values separated by ";" in order from top to bottom, left to right;
I'm actually embarrassed I have to ask this "easy" question but Im not getting results lol. Might be the structure of the returned resource Im not getting, who knows.
I dont want to have to plugin in row or fields names, I just want to iterate through and display it, regardless of the result.
while($row = mysql_fetch_assoc($result)) {
// Your code goes here...
// OR
echo "<pre>"; print_r($row); echo "</pre>";
}
check: http://php.net/manual/de/function.mysql-query.php
If you want to display specific columns of the result:
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
or just the whole set of result:
$result_set = mysql_fetch_assoc($result) or die(mysql_error());
echo '<pre>';var_dump($result_set);echo '</pre>';
Here is a modified version of the answer I was given, that fits my specifications of being Comma delimited. Just in case their are others looking for the same thing.
$result = mysql_query($query) or die("Error: Cant query database");
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($line as $col_value)
{
echo $col_value.";";
}
}
I am trying to loop though my users database to show each username in the table in their own row. I can only get it to show one user but loops through this the number of rows there are. Code is below
<?php
require_once ('../login/connection.php');
include ('functions.php');
$query = "SELECT * FROM users";
$results=mysql_query($query);
$row_count=mysql_num_rows($results);
$row_users = mysql_fetch_array($results);
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
?>
Thanks
mysql_fetch_array fetches a single row - you typically use it in a while loop to eat all the rows in the result set, e.g.
echo "<table>";
while ($row_users = mysql_fetch_array($results)) {
//output a row here
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You're only fetching one row:
$row_users = mysql_fetch_array($results);
You're never calling a fetch again so you're not really looping through anything.
I'd suggest changing your loop to the following:
echo "<table>";
while ($row = mysql_fetch_array($results)) {
echo "<tr><td>".($row['email'])."</td></tr>";
}
echo "</table>";
The while loop will loop through the results and assign a row to $row, until you run out of rows. Plus no need to deal with getting the count of results at that point. This is the "usual" way to loop through results from a DB in php.
In the new MYSQLI, I use this coding
$query = "SELECT * FROM users";
$results=mysqli_query($con,$query);
$row_count=mysqli_num_rows($results);
echo "<table>";
while ($row = mysqli_fetch_array($results)) {
echo "<tr><td>".($row['id'])."</td></tr>";
}
echo "</table>";
mysqli_query($con,$query);
mysqli_close($con);
Your problem is in this line:
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
You're echoing out a <table> tag again. Remove that so your code looks like this:
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You don't need to output a table within a table the way you're doing it.
$result = mysql_query("SELECT `email` FROM `users`");
$num_emails = mysql_num_rows($result);
echo "<table><caption>There are/is $num_emails email(s)</caption>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>{$row['email']}</td></tr>";
}
echo '</table>';
Something like that should work.