PHP Notice: Undefined offset 1 [duplicate]

2020-05-03 10:03发布

问题:

I am trying to fetch an id column from database sequentially. I have written this code but it didn't work.

 $connection = mysqli_connect($servername,$username,$password,$dbname);
if(!$connection)
    die("Database connection failed: " . mysqli_connect_error());

$query = "SELECT ID FROM channel "; 

if($result = mysqli_query($connection,$query))
{
    $count = mysqli_num_rows($result);// it will start from the first row and continue with others...
    //fetch one and one row
    while($row=mysqli_fetch_row($result))
    {
        for($i=0; $i<$count; $i++)
        echo "<a>$row[$i]</a>";
    }
    //free result set 
    mysqli_free_result($result);

}
mysqli_close($connection);

So, this code gives me this error:

Notice: Undefined offset: 1 in C:\xampp\htdocs\gt\fetch_channel.php on line 24

Can anyone help me about that ?

回答1:

the problem is: There is no $i index in $row I'm not sure what would you like, but I think you would like something like this:

 $connection = mysqli_connect($servername,$username,$password,$dbname);
if(!$connection)
    die("Database connection failed: " . mysqli_connect_error());

$query = "SELECT ID FROM channel "; 

if($result = mysqli_query($connection,$query))
{

    //fetch one and one row
    while($row=mysqli_fetch_row($result))
    {

        echo "<span>".$row['id']."</span><br/>";
    }


}
mysqli_close($connection);