With the code below I have to report to a table of rows from a database.
But in addition to the lines that I need, is displayed containing parts in php code (noName).
I try to keep only the echo tag
echo $row[0];
but i get the error
Notice: Undefined offset: 1 in test.php on line 16
MYSQL
ID | Team
------------------------------
1 test1
2 test2
3 test3
PHP
<?php
$connection = mysqli_connect("YourHost","user","password","dbName") or die('connection to DB failed');
$query = mysqli_query($connection,"SELECT team FROM s1");
while ($row = mysqli_fetch_array($query,MYSQLI_NUM)) {
?>
<table>
<tr>
<td><p> team name <?php if(isset($row[0])){
echo $row[0];
}else{
echo 'noName';
} ?></p></td>
</tr>
<tr>
<td><p> team name <?php if(isset($row[1])){
echo $row[1];
}else{
echo 'noName';
} ?></p></td>
</tr>
<?php } ?>
Output in php page:
test1
noName
test2
noName
You are selecting just 1 field that is team
from the database. So in your code PHP if you write $row[0]
is the same if you write $row['team']
.
$row[1]
so is empty.
If you want print the name of all team you have to write this code:
...
echo "<table>";
while ($row = mysqli_fetch_array($query,MYSQLI_NUM)) {
?>
<tr>
<td><p> team name <?php echo $row[0]; ?></p></td>
</tr>
i would write your code like this:
<?php
$connection = mysqli_connect("YourHost","user","password","dbName") or die('connection to DB failed');
$query = mysqli_query($connection,"SELECT team FROM s1");
if($query) {
echo "<table>";
while ($row = mysqli_fetch_array($query,MYSQLI_NUM)) {
echo "<tr>";
echo "<td><p> team name " . $row['team'] . "</p></td>";
echo "</tr>";
}
echo "</table>";
}
?>
Look at your SQL query:
"SELECT team FROM s1"
You're only selecting one value from the table, the value called team
. So each row returned by this query will have only one value. That value is in $row[0]
. Hence, there is no value in $row[1]
. In order to populate $row[1]
with something, your SELECT
will need at least a second value:
"SELECT team, someOtherValue FROM s1"
Of course, if your table has no other values, then there's nothing else to display...
It looks like you're trying to display the same conceptual value twice in each loop. Why? Generally each iteration of the loop would add a single row to the HTML table, not two rows. Something like this:
while ($row = mysqli_fetch_array($query,MYSQLI_NUM)) {
?>
<table>
<tr>
<td><p> team name <?php if(isset($row[0])){
echo $row[0];
}else{
echo 'noName';
} ?></p></td>
</tr>
<?php } ?>