Basic MySQL connection and query with PHP
I use this almost on a daily basis, and yet I can’t commit it to memory. So I don’t have to go searching for it each time I need to write it…
$databaseName = “YOURDATABASENAME“;
$dbconnection = mysql_connect(”localhost”, “DATABASE-USERNAME“, “DATABASE-PASSWORD“) or
die (’I can?t connect to the database.’);
mysql_select_db($databaseName,$dbconnection);
$value = “SOMEVALUE“;
$query = sprintf(”SELECT FIELDNAME from TABLENAME where FIELDNAME=’%s’;”, $value);
$result = mysql_query($query);
$totalNum = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) {
echo $row['FIELDNAME'];
}
////////OR//////
for ($i =0; $i < $totalNum; $i++) {
$row = mysql_fetch_array($result);
echo $row['FIELDNAME'];
}
This entry was posted
on Wednesday, September 17th, 2003 at 6:59 am and is filed under Script snippet.
You can follow any responses to this entry through the RSS 2.0 feed.
Both comments and pings are currently closed.
September 17th, 2003 at 10:26 am
fetch, not fecth
September 17th, 2003 at 10:37 am
ARGH! Good catch. code is fixed.
September 17th, 2003 at 6:06 pm
You shouldn’t be using sprintf() in this context, as you’re not doing any special formatting. Just use simple string concatenation. This is one of the Top 21 PHP programming mistakes: http://www.zend.com/zend/art/mistake.php#Heading4
September 17th, 2003 at 6:19 pm
Hmm… my experience is that this works better when constructing query statemtents. Simple string concatenation does not seem to work consistently.
September 17th, 2003 at 6:44 pm
In the above example, it’s simple enough that concatenation works (i just tested it) - however, I’ve gotten into the habit of using sprintf because, for reasons I can never figure out - sometimes it won’t construct the query statement unless I use sprintf.
September 22nd, 2003 at 2:26 am
Curious. Never had a problem with such, but I’ll take your word for it.
April 6th, 2004 at 1:26 pm
Warning: Supplied argument is not a valid MySQL result resource in ….etc.
Your code does not work.
May 11th, 2004 at 10:49 pm
This is a good code, great for beginers to use…