OsitoFour Posted Thursday at 02:56 PM Share Posted Thursday at 02:56 PM I am upgrading from an older PHP and am having difficulty with this particular piece of code. I use to be able to refer to elements of an array pulled from a MySQL dB by their number placement within that dB table. That no longer seems to be functioning … at least not with the code I’ve been using. <?php include 'r_open_link.php'; $query = "SELECT * FROM ember_seating_charts WHERE course_id = 204"; $result= $pdo->query($query); $row = $result->fetch(); print "Cell 6: ".$row[6]." should be ".$row['cell1']."<br>"; ?> This is a test script I wrote to check the functionality of my code. $row[6] and $row[‘cell1’] should both be the same value because ‘cell1’ is the 7th field in that table. The code returns the proper value for $row[‘cell1’], but gives the error “Warning: Undefined array key 6 in /home/jandrews/public_html/test_gen.php on line 8” now. Thanks. Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted Thursday at 08:17 PM Solution Share Posted Thursday at 08:17 PM There are several FETCH modes in PDO. The most usual is to set the default to PDO::FETCH_ASSOC so the row arrays are indexed by field name. This is normally set in your connect options. However, even if the default is set it can be overridden when required. So... $row = $result->fetch(PDO::FETCH_NUM) will allow you to use $row[6]. Quote Link to comment Share on other sites More sharing options...
requinix Posted Thursday at 11:02 PM Share Posted Thursday at 11:02 PM That said, how the heck do you know what "6" means? Use column names instead. Quote Link to comment Share on other sites More sharing options...
Barand Posted Thursday at 11:14 PM Share Posted Thursday at 11:14 PM 9 minutes ago, requinix said: how the heck do you know what "6" means? It's as meaningful as "cell1" - but column names like that ring other warrning bells, like unnormalised tables with data stored like spreadsheets Quote Link to comment Share on other sites More sharing options...
OsitoFour Posted Friday at 03:35 PM Author Share Posted Friday at 03:35 PM Thank you! It worked. I did, however, look at the FETCH modes you linked to and chose FETCH_BOTH as I need both. If I were to write the whole script all over again I would use ASSOC here, but when I wrote this particular tool (it’s a seating chart) I didn’t know how to do something like this ${‘cell’.$count} and I’m spending so much time re-writing so much code to bring my PHP5 code up to PHP8 functionality standards that I just can’t re-write the entire tool the way I’d like to. THANK YOU for your help!!! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.