1

I am learning MySQL/php through online tutorials and have found the techniques and syntax different from different sources.

In one tutorial, I enter data (from an HTML form) like this:

$table = "ENTRIES";
$sql    = "INSERT INTO $table SET
TITLE   = '$_POST[title]',
SUMMARY = '$_POST[summary]',
CONTENT = '$_POST[content]'";
$query  = @mysql_query($sql);

And in another, like this:

mysql_query("
    INSERT INTO `posts` SET
        `title` = '{$_POST['title']}',
        `contents` = '{$_POST['post']}'
");}

They both work, and I understand the different variable arrangements. BUT I have the following questions, probably all related. (I gather that @mysql_query suppresses error messages, SO if that is what is going on here, can you please explain how it is functioning and what is actually proper syntax?)

1) In the first example, in @mysql_query(), it doesn't matter if I use ("") or ('') ... but in the second example, in mysql_query(), it breaks if I use (''). In fact it tells me that there is an unexpected {, which leads to my next question: 2) What is the deal with the {} in the second example? They don't seem to be doing anything, but it breaks without them. 3) In the first example, is breaks if I enclose title, summary, and content in single quotes ''. In the second, with 'title' and 'post', it breaks if I don't!

Any explanations or references/links comprehensible to a beginner would be much appreciated!

drenl
  • 1,321
  • 4
  • 18
  • 32
  • The tutorial you're using will teach you to use [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) instead of [its modern replacements](http://php.net/manual/en/mysqlinfo.api.choosing.php). Find a better tutorial (try [this one](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers) ). – DCoder May 31 '13 at 04:15
  • Ok. I will read these. Thanks. – drenl May 31 '13 at 04:16

1 Answers1

1

Run far away from this tutorial and fine one that uses PDO / mysqli and explains how to properly parameterize queries.

Anyway, your questions are PHP specific and have to do with variable interpolation in strings. In quoted strings (") variables are interpolated, and arrays can be accessed via:

"{$var['value']}"
"$var[value]"

Either one is valid ... they function identically and it's up to personal preference which one you should use.

mysql_query takes a string as an argument, so it actually makes no difference how you build it. Both of the above are valid. Using @ makes no difference -- in fact, you shouldn't use it, and you should properly handle possible errors and check mysql_error

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Thanks. I don't really get this yet but I will search on the topic. If you have a reference you can recommend regarding these php topics I would be grateful. – drenl May 31 '13 at 04:33