Doubt about SQL in PHP

0

I am currently performing a job that needs to access the database, and I had a lot of difficulty in some queries , including the query of UPDATE . But after much searching I found a solution and wanted to ask what the difference is, which is better, etc.

I used

$sql = mysql_query("UPDATE tabela SET campo1 = ' ".$1." ', campo2 = ' ".$2." ' WHERE user = ' " .$3. " ');

But what worked was:

$sql = mysql_query("UPDATE tabela SET campo1 = '$1', campo2 = '$2' WHERE user=$3");

In other words, I removed endpoints, quotation marks, etc. Does it make any difference? I used with the dots and quotation marks in queries of type SELECT and INSERT and it worked.

    
asked by anonymous 23.03.2016 / 19:53

1 answer

1

In PHP, the operator. (dot) concatenates strings, and strings can be delimited with double or single quotation marks. In MySQL, strings are always delimited by single quotes. In the sections presented, the PHP string is double-quoted.

The first snippet should not have worked because you accidentally added whitespace before and after the value of the inserted variable. Illustrating with code:

$nome = "João da Silva";

"' " . $nome . " '" results in ' João da Silva ' .

"'$nome'" results in 'João da Silva' .

The second part works as it should. I recommend changing $1 , $2 , etc., by representative names of table columns.

    
23.03.2016 / 22:17