/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Simple PHP help, I need to clean up this code.

This is a real basic question, I just don’t have time to mess around with it.
So, what I’m trying to do is get all the information from one table, but than create variables for each column of each row, because I want to be able to move them around the page, not simply echo or rewrite them linearly.

I got this to work just fine, but I think my code could be simplified, cleaned up a bit, shortened.

Here’s what I got:

<?php
$username = “myusername”;
$password = “mypassword”;
$hostname = “localhost”;
$dbh=mysql_connect (“localhost”, “myusername”, “mypassword”) or die (‘I cannot connect to the database because: ‘ . mysql_error());
$selected = mysql_select_db(“mydatabase”,$dbh) or die(“Could not select first_test”);

$result = @mysql_query(“SELECT * FROM mytable ORDER BY name”);

$row1 = mysql_fetch_array($result);
$r1date = ($row1[‘date’]);
$r1band = ($row1[‘band’]);
$r1instrument = ($row1[‘instrument’]);

$row2 = mysql_fetch_array($result);
$r2date = ($row2[‘date’]);
$r2band = ($row2[‘band’]);
$r2instrument = ($row2[‘instrument’]);

$row3 = mysql_fetch_array($result);
$r3date = ($row3[‘date’]);
$r3band = ($row3[‘band’]);
$r3instrument = ($row3[‘instrument’]);

mysql_close($dbh);
?>

See, I’m fetching an array every time. I don’t know too much about this, could I get it to automatically create variable names?

For instance, I’m having to rename every element from row 1 individually, and the same with row 2 and row 3.

If you need more info, maybe I can help.
Please e-mail me immediately if you can help, much appreciated!
[email][email protected][/email]

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@bathurst_guyFeb 10.2007 — Use a foreach loop. One of the basic things you learn when you learn PHP.
Copy linkTweet thisAlerts:
@NightShift58Feb 10.2007 — Use:[code=php]<?php
WHILE ($row = mysql_fetch_array($result)) {

}
?>[/code]
×

Success!

Help @robmarston 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.18,
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,
)...