1
Brad
Difference between methods of SQL queries
  • 2004/3/15 16:55

  • Brad

  • Not too shy to talk

  • Posts: 150

  • Since: 2003/12/4


I noticed that XOOPS 2.0.6 prefers coding SQL queries with the sprintf function as follows:

$sql = sprintf("DELETE FROM %s WHERE id = %u", $xoopsDB->prefix("partners"), $id);

Prior to 2.0.6 I believe XOOPS would have coded it as follows:

$sql = "DELETE FROM ".$xoopsDB->prefix("partners")." WHERE id = $id";

Why the difference? Is there a benefit to using the new method?

Brad

2
Dave_L
Re: Difference between methods of SQL queries
  • 2004/3/15 17:05

  • Dave_L

  • XOOPS is my life!

  • Posts: 2277

  • Since: 2003/11/7


It's only a matter of personal preference. Using sprintf is more time-consuming than simple string concatenation, but I doubt that the difference is significant.

My preference is:

le="color: #000000"><?php $table = $xoopsDB->prefix("partners"); $xoopsDB->query("DELETE FROM $table WHERE id = '$id'");


Or for complex queries that don't fit nicely on one line:

le="color: #000000"><?php $result = $xoopsDB->query(" SELECT a, b, c FROM $table WHERE d = 'foo' AND e = 'bar' ORDER BY f DESC LIMIT 30 ");


Note that having a line break in between the opening " and SELECT requires a trivial change to class XoopsMySQLDatabaseProxy::query.

I think the primary objective should be to make the code readable.

3
Brad
Re: Difference between methods of SQL queries
  • 2004/3/15 17:47

  • Brad

  • Not too shy to talk

  • Posts: 150

  • Since: 2003/12/4


le="color: #000000"><?php $xoopsDB->query("DELETE FROM $table WHERE id = [color=FF0000]'$id'[/color]");

Which leads me to another question (I'm relatively new to the PHP world), do you need the apostrophes around $id? It seems like I've seen the same type of query with and others without the apostrophes.

4
Dave_L
Re: Difference between methods of SQL queries
  • 2004/3/15 17:55

  • Dave_L

  • XOOPS is my life!

  • Posts: 2277

  • Since: 2003/11/7


The apostrophes (or quotes) are required for string values, but are optional for numeric values.

Quoting a number will avoid a MySQL syntax error (missing value) if the numeric variable is undefined, which may (or may not) be desirable.