/    Sign up×
Community /Pin to ProfileBookmark

MySQl Field names to variables

I have a MySQL table like so

id
name
email

(one entry could be like [1,Bob,[email protected]] respectively)

What I want to do is run a script through a user table, pulling all the data, and setting the data to variables like the field names they we’re pulled from

For example
$id = 1
$name = “Bob”
$email = “[email protected]

I did it once before, yet that was like 2 years ago, and I just started up again after taking a break…and it’s not coming back so fast.

The way I had it set up before is that I could append a string before the field name, like so: (using ‘user_’ so variables don’t get mixed up in the script somewhere)

$user_id = 1
$user_name = “Bob”
$user_email = “[email protected]

I think it used a loop, and the eval() statement, yet other than that, I’m lost

Doubt it will help yet here’s what I have so far:

[code=php]
$val = $db->query(“SELECT * FROM users WHERE id = ‘$userid'”);
while($vals = $db->fetch_array($val)){
eval(“$user”.$vals[0].” .= “$vals[0]”;”);
}
[/code]

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@shimonSep 24.2004 — You're possibly looking for [url=http://www.php.net/extract]extract()[/url].

So, for example:

[code=php]<?php

$result = mysql_query(...);
$row = mysql_fetch_assoc($result); // or $db->fetch_array

extract($row, EXTR_PREFIX_ALL, 'user',);

// gives you

$user_id = 1
$user_name = "Bob"
$user_email = "[email protected]"

?>[/code]


The prefix is optional, if you don't want to use it - but you're right, it is useful to avoid clobbering other variables with the same name.
Copy linkTweet thisAlerts:
@ShuklarauthorSep 24.2004 — *cheer*

Thank you! That's precisely what I need.

*pats shimon on the back*
×

Success!

Help @Shuklar spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...