$sql = 'INSERT INTO joke SET
joketext="' . $joketext . '",
jokedate="today's date"';
i don’t understand why the joketext=“’ . $joketext . '”, use the single quote and the concatenation . i feel those are a surplus, use this is joketext="$joketext ", ok, but when i test it ,it’s show an error, anyone can tell me the reason.any tips would be appreciated.
In that example the single quotes are part of the PHP used to create the SQL as a string. The double quotes are actually part of the SQL statement that gets sent to MySQL.
/* the single quotes are needed to wrap the string */
$animal = 'cat';
/* this string has double quotes as part of the string */
$quote = 'John said "blah" in response to the question';
The reason for the concatenation is so that the value of $joketext gets inserted into the query. Variables inside single quotes aren’t parsed, so without the concatenation you’d get $joketext appear literally in the DB instead of the actual joke text.
It could be rewritten like this:
$sql = "INSERT INTO joke SET joketext='$joketext', jokedate='2010-03-18'";
It’s not necessary for a simple variable. (You can use it if you want, makes no difference).
When the curly braces are more useful is if you are referencing an object property, or an array value
$people[0]['name'] = 'John Doe';
$people[0]['job'] = 'Helicopter Pilot';
$people[1]['name'] = 'Helen Doe';
$people[1]['job'] = 'Horse Whisperer';
echo "{$people[1]['name']} is a good {$people[1]['job']}";
//Object oriented example
class Example
{
protected $people = array('John', 'Bob', 'Ted');
public function third_person() {
return "The third person is {$this->people[2]}";
}
}
$obj = new Example();
echo $obj->third_person();