Jump to content

PHP fetch SQL result, without using column name

venomtail

Curious. When querying SQL data in PHP, if I want to output data from a table result with a fetch_assoc, I'd have to always use column names. If I know the column position, is there not an option to just get the row for the position of the column rather than the name of it?

 

If an SQL table exists like this:

ID, DOB, first_name, last_name

and I want Date of birth and I know it'll always be the 2nd column, a pseudocode like it would be something like:

$row[1];

instead of how you'd always have to reference it:

$row["DOB"];

Sort of getting annoyed with how rigid PHP is when it comes to SQL. If I could just use positions I could make my code far more flexible instead of hardcoding each column on its own. 

 

On second thought, I feel like this is a non issue and I'm just looking at a roundabout way of overcomplicating my code. Am I going insane?

Desktop: Ryzen 7 5800X3D - Kraken X62 Rev 2 - STRIX X470-I - 3600MHz 32GB Kingston Fury - 250GB 970 Evo boot - 2x 500GB 860 Evo - 1TB P3 - 4TB HDD - RX6800 - RMx 750 W 80+ Gold - Manta - Silent Wings Pro 4's enjoyer

SetupZowie XL2740 27.0" 240hz - Roccat Burt Pro Corsair K70 LUX browns - PC38X - Mackie CR5X's

Current build on PCPartPicker

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, venomtail said:

and I want Date of birth and I know it'll always be the 2nd column, a pseudocode like it would be something like:

$row[1];

instead of how you'd always have to reference it:

$row["DOB"];

what PHP version are you using because you can definitively reference by index the column like

Quote

$row[1];

 

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, venomtail said:

if I want to output data from a table result with a fetch_assoc.

...

Sort of getting annoyed with how rigid PHP is when it comes to SQL

Make sure you understand the differences in function names and their uses.

 

mysqli_fetch_assoc returns a row from the result set and populates an array using the column name as array keys, ie $row['DOB'].

mysqli_fetch_row, will return a row from the result set and populate an array using the column position as the index, ie $row[1]

 

mysqlI_fetch_all, with the 'mode' set to MYSQLI_BOTH, will returns a row from the result set and populates an array with both types. You can access either by column name or column index.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×