Search code examples
phpmysqlhtml-tableundefinedoffset

Undefined offset in table PHP


Can someone solve my problem? I got this error:

Notice: Use of undefined constant qty - assumed 'qty' in C:\Program Files (x86)\xampp\htdocs\dede\transaksi.php on line 65
Notice: Undefined offset: 3 in C:\Program Files (x86)\xampp\htdocs\dede\transaksi.php on line 65

on this script, I want to multiply between cost and qty, anyone know?

$select=mysql_query("Select nota.id_item,nota.qty,item.nama_item,item.cost_item FROM nota,item WHERE nota.id_item = item.id_item");
       while($data=mysql_fetch_array($select)){
       $sub=$_POST[$data[qty]] * $_POST[$data[cost_item]];
        echo"<tr>";
          echo"<td height=20 >$data[id_item]</td>";
          echo"<td height=20 >$data[nama_item]</td>";
          echo"<td height=20 >$data[cost_item]</td>";
          echo"<td height=20 >$data[qty]</td>";
          echo"<td height=20 >$data[qty]*$data[cost_item]</td>";
          echo"<td><a href=deleten.php?id=$data[id_item]>X</a></td>";
         echo"</tr>";}

Solution

  • Let's break this down...

    $select = mysql_query("Select nota.id_item,nota.qty,item.nama_item,item.cost_item FROM nota,item WHERE nota.id_item = item.id_item");
    while($data=mysql_fetch_array($select)) {
    

    At this point, your $data variable should have 8 elements to it. Since you used mysql_fetch_array(), you'll have both numeric and associative keys. That is, your keys will be: 0, 1, 2, 3, id_item, qty, nama_item, cost_item, and you can reference them either like this: $data[1], or like this: $data['qty'] (since they are indexed in order of the original query, the values of these two examples should be the same).

    Now, I don't exactly know why you're using $_POST... If you wanted to get the cost multiplied by the quantity for the values you got from the database, you'd just do:

    $sub = $data['qty'] * $data['cost_item'];
    

    By the way, one more problem you're going to face is that PHP won't do string substitution for array members... at least not the way you have it here:

    echo"<td height=20 >$data[qty]</td>";
    

    Given that you fix $data[qty] to $data['qty'], you're still going to need to surround the whole thing in curly braces in order for it to print. Otherwise, you'll get a parsing error:

    echo"<td height=20 >$data['qty']</td>";    // Bad
    echo"<td height=20 >{$data['qty']}</td>";  // Good