Jump to content

Using PDO


Lyleyboy

Recommended Posts

Hey all,

 

I'm just starting to get on the PDO bandwagon with PHP.

 

One thing I do a lot is to fetch the result of a query straight into a variable using list. Something like

list($name) = mysql_fetch_row(mysql_query("SELECT name FROM names WHERE userID='1'"));

 

Is there a similar thing I can do with PDO rather than having to loop through with a while or similar.

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/275367-using-pdo/
Share on other sites

Yeah I accept that and I always code round it, to ensure that the value is present and in the correct format.

 

So what's the easiest way then? Do I still have to loop through, even though there will only be one record posted.

 

I'm kind of hoping there will be an easier way.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/275367-using-pdo/#findComment-1417211
Share on other sites

You shouldn't accept it, that is horrible coding practice.

Both the SQL statement and the mysql_query() return should be stored in variables and checked.

But, to address you question, use that example without the looping logic if the query is to grab only 1 row.

Link to comment
https://forums.phpfreaks.com/topic/275367-using-pdo/#findComment-1417215
Share on other sites

While I agree with @trq, let's just be clear about this looping. It is never required that you loop through a result set. If you know it returns a single row (or only want the first row), you can leave out any while or for processing and just fetch the first row.

 

Well, that's the way it is/was in mysql, and I do it that way with mysqli. I have not played with PDO yet, but I see no reason this should not apply there as well.

 

Link to comment
https://forums.phpfreaks.com/topic/275367-using-pdo/#findComment-1417243
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.