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

8 Responses to “Basic MySQL connection and query with PHP”

  1. Happy Says:

    fetch, not fecth

  2. Jennifer Says:

    ARGH! Good catch. code is fixed. :)

  3. Jordan Says:

    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 Says:

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

  5. Jennifer Says:

    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 Says:

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

  7. ScriptKiddie Says:

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

    Your code does not work.

  8. champion Says:

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