Doubt about SQL in PHP

Asked

Viewed 50 times

0

I am currently carrying out a work that needs to access the database, and I had a lot of difficulty in some darlings, among them the query of UPDATE. But after much searching I found a solution and I wanted to ask what is the difference, 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 dots, quotation marks etc. Does it make a difference? I used with dots and quotation marks on darlings of the kind SELECT and INSERT and it worked.

  • 1

    Its variable flame $1? no way is legal pq uses obsolete functions and removed from newer versions of PHP(7)

  • No. I was just trying to create an example haha

  • I always thought the point was to differentiate php from query. the quotes I think are because of being a query, because in Phpmyadmin is also accurate.

  • 2

    This question is making a mess between query and operation string in PHP. I suggest learning each thing separately.

  • So the point serves to concatenate(join) strings(texts), in php briefly the difference between single and double quotes is, the first type does not read the value of a varive in already the second yes. Example: $v = 'valor'; echo '$valor<br>'; echo "$valor"; For more details see that question. In SQL the difference between them is that simple values are usually delimited and double values can be the escape character in column names with keywords/reserved words. If you have any questions put there in the comment.

  • the error that this taking is that it has a space between the single and double quotes, change ' ".$1." ' for '".$1."' and in the other tbm

Show 1 more comment

1 answer

1

In PHP, the . (dot) operator concatenates strings, and in strings can be bounded with double or single quotes. In Mysql, strings are always delimited by single quotes. In the snippets shown, the PHP string is double quoted.

The first section must not have worked because, unintentionally, it added white space 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 section works as it should. I recommend changing $1, $2, etc., by representative names of table columns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.