scriptygoddess

17 Sep, 2003

Basic MySQL connection and query with PHP

Posted by: Jennifer In: Script snippet

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'];
}

8 Responses to "Basic MySQL connection and query with PHP"

2 | Jennifer

September 17th, 2003 at 10:37 am

Avatar

ARGH! Good catch. code is fixed. :)

3 | Jordan

September 17th, 2003 at 6:06 pm

Avatar

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

4 | Jennifer

September 17th, 2003 at 6:19 pm

Avatar

Hmm… my experience is that this works better when constructing query statemtents. Simple string concatenation does not seem to work consistently.

5 | Jennifer

September 17th, 2003 at 6:44 pm

Avatar

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.

6 | Jordan

September 22nd, 2003 at 2:26 am

Avatar

Curious. Never had a problem with such, but I'll take your word for it.

7 | ScriptKiddie

April 6th, 2004 at 1:26 pm

Avatar

Warning: Supplied argument is not a valid MySQL result resource in ….etc.

Your code does not work.

8 | champion

May 11th, 2004 at 10:49 pm

Avatar

This is a good code, great for beginers to use…

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements