-2

I'm about to pull my hair out. I can't get the undefined index to go away. Basically where it says echo htmlspecialchars($r['serial']) I want it to list the item out of the database table.

<?php
    try{    
        $conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
        $sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
        $q = $conn->prepare($sql);

        $q->setFetchMode(PDO::FETCH_OBJ);

        while ($r = $q->fetch());
    } catch (PDOEException $pe) {
        die("Could not connect to the database" . $pe->getMessage());
    }   
?>      

</div>

<?php
$r = $q->fetchAll();
echo htmlspecialchars($r['serial'])
?>
Machavity
  • 29,816
  • 26
  • 86
  • 96
John Haag
  • 11
  • 3

2 Answers2

1

You are referring to the result as an associative array where you expect to have the key 'serial'. This is the behavior of PDO::FETCH_NAMED, not PDO::FETCH_OBJ. Just use the right fetch mode, and you should be fine:

$q->setFetchMode(PDO::FETCH_NAMED);
Mureinik
  • 277,661
  • 50
  • 283
  • 320
0

see the below code, the fetchAll will get the results in an associative array, so you can get the data like $row['serial'] and use it later. also added the execute() on the pdo statement obj.

<?php

try{    

    $conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);

    $sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";

    $q = $conn->prepare($sql);


    $q->execute(); // make sure to add this


    $results = $q->fetchAll();

    foreach($results as $row) {
        echo htmlspecialchars($row['serial']) . "<br>";
        //if you want to use the serial later, just store it into an array
        $serials [] = htmlspecialchars($row['serial']);
    }

// while ($r = $q->fetch()); this is not needed because of the fetchAll statement above

}
catch (PDOEException $pe) {
        die("Could not connect to the database" . $pe->getMessage());
    }
?>

</div>

<?php
    //$r = $q->fetchAll(); not needed here, we did it above already
?>

<?php 
    //echo htmlspecialchars($r['serial']); use your array from above
    print_r($serials);
?>

let me know if it helps

Alex Andrei
  • 7,137
  • 3
  • 26
  • 41
  • Oh my goodness! Thank you so much. I know have data on my page! – John Haag Jun 25 '15 at 13:06
  • @JohnHaag glad to be of assistance – Alex Andrei Jun 25 '15 at 13:26
  • Is there a way to format the data in a table instead of with
    ? Since I've corrected my code the way you showed I've added all of my other items to arrays and am wanting to make it where serial, model, etc are column headers with the data listed below. I've tried the following, but it just breaks the application. echo "" htmlspecialchars($row['serial']) . ""; echo " htmlspecialchars($row['model']) . "";
    – John Haag Jun 25 '15 at 16:12