-1

I'm new to php.

When I run this script I get the error message:

Undefined offset: 0

for the line: while ($row = mysql_fetch_assoc($result)) { echo $row['0'];

    <?php

    if (!$link = mysql_connect('localhost', 'root', '')) {
        echo 'Could not connect to mysql';
        exit;
    }

    if (!mysql_select_db('first_db', $link)) {
        echo 'Could not select database';
        exit;
    }

    $sql    = 'SELECT * FROM users WHERE id = 3';
    $result = mysql_query($sql, $link);

    if (!$result) {
        echo "DB Error, could not query the database\n";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }

    while ($row = mysql_fetch_assoc($result)) {
        echo $row['0'];
    }

    mysql_free_result($result);

    ?>

Here is another script which connects to the database, here the syntax $row['0'] is working.

<?php
//Step1
 $db = mysqli_connect('localhost','root','','first_db')
 or die('Error connecting to MySQL server.');
?>

<html>
 <head>
 </head>
 <body>
 <h1>PHP connect to MySQL</h1>

<?php
//Step2
$query = "SELECT * FROM  users";
mysqli_query($db, $query) or die('Error querying database.');

//Step3
$result = mysqli_query($db, $query);
//$row = mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result)) {
 echo $row[0] . ' ' . $row[1] . ': '. $row[2] .'<br />';
}
//Step 4
mysqli_close($db);
?>

</body>
</html>

How come the syntax row['0'] works for the second script but not the first ?

btw my database is called first_db and the table called users. It has 3 columns; named id, username, and password.

chris85
  • 23,846
  • 7
  • 34
  • 51
demonslayer1
  • 741
  • 2
  • 16
  • 24
  • 1
    Read the manual for `mysql_fetch_assoc()` and `mysqli_fetch_array()` and see what they return. – Rizier123 Oct 29 '16 at 23:22
  • 1
    Why are you reverting to mysql_ functions when (1) they're officially deprecated and (2) the mysqli_ counterparts are working? – Terry Oct 29 '16 at 23:31

1 Answers1

0

No. The reason it's not working is actually a combination of two things. First, the use of mysql_Fetch_assoc() which returns (as https://stackoverflow.com/users/6946846/andrew-wilson mentioned) a associative array. Second is that you use $row['0'] which is NOT the same as $row[0] - the first checks for a an element in the array with the name 0, as a string, while the second checks for the first (numerical) key in the array.

Community
  • 1
  • 1
junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33