What is the .= (dot equals) operator in PHP? [duplicate] - php

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 8 years ago.
What does the following line mean, particularly the operator .=?
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
in the code
<?php
$conn = pg_pconnect("dbname=publisher");
// these statements will be executed as one transaction
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
pg_query($conn, $query);
?>
It seems to make some sort of array such that the last command processes first the first query and then the second.

This is the concatenate assignment operator. It will concatenate or add to the end of the string. So:
$a = "Hi!";
$a .= " I";
$a .= " love";
$a .= " StackOverflow";
$a .= " a";
$a .= " lot";
echo $a; // echos "Hi! I love StackOverflow a lot"
In your case
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
echo $query;
/* echos "UPDATE authors SET author=UPPER(author) WHERE id=1; UPDATE authors SET author=LOWER(author) WHERE id=2; */

It means $query = $query . "UPDATE authors SET author=LOWER(author) WHERE id=2;";
So it appends the String to the Query Variable.

Your question is about the operator .=. It is a shorthand to a string concatenation followed by an assignment.
On assigment by operation operators
There is a family of operators we can call assignment by xyz, where xyz here represents a binary operation on operands of the same type, such as addition, subtraction, concatenation.
So, let's say we have an operator ⊕: int*int → int, meaning that it takes a pair of ints and produces another one:
⊕(a, b) = a ⊕ b
Let's say we want to calculate a⊕b and store the results on the variable a. We can do so by:
a = a ⊕ b
But we do this so often when coding that an operator was created to represent the line above. You should take it as a single operation that does both the ⊕ operation and the assignment ( = ) with a single call:
a ⊕= b ⇔ a = a ⊕ b.
Some examples
So, in your case, you have a .= operator. Now that you know about assignment by operation operators, you can guess that:
$query = "Hello, "
$query .= "World!";
is the same as:
$query = "Hello, "
$query = $query . "World!";
See?
Now, another frequent use of this kind operators are the += and -= versions.
However, abuse of this kinds of operators may lead to less readable code (especially when dealing with "low level" operators acting on bits, for example).

.= simply means "append". This
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
…results in
$query == "UPDATE authors SET author=UPPER(author) WHERE id=1;UPDATE authors SET author=LOWER(author) WHERE id=2;"

it separates the updates with ; and executes both of them

Concatenates the string... so $query becomes:
"UPDATE authors SET author=UPPER(author) WHERE id=1;UPDATE authors SET author=LOWER(author) WHERE id=2;"

Related

How to Concatenate table name with with a variable value in mySQL

I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :
//that's how I get my variable the value for example is = 3
$pid = $GLOBALS["localid"];
//the table name for example is tablename_3
$strTable = "tablename_" .$pid;
//here's how the query should look like
$query = "SELECT * FROM . $strTable . where .....;
I'm making a mistake somewhere but can't figure it out and would appreciate a little help please
Remove the dots and also make sure you have single quotes aroung where
$query = "SELECT * FROM $strTable where '.....';
Besides the comments about do or don't build your queries like this...
You're not closing the quotes properly.
$query = "SELECT * FROM . $strTable . where .....; //Double quote not closed.
should be:
$query = 'SELECT * FROM' . $strTable . 'where .....'; //Single quoted strings concatenated with variable.
or
$query = "SELECT * FROM $strTable where ....."; //Variable inside double quoted string.

Dynamic sql search in php

Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !

How can I use multiple values in a "where" clause? [duplicate]

This question already has answers here:
MySQL query check two value in one column
(2 answers)
Closed 2 years ago.
My code and my database are the following
$my=mysql_query("select * from users where email='ids'")or die(mysql_error);
id___email___________pass
1 abc#d.com 123
2 xxx#x.uk 333
3 ah#cc.com 555
I need a syntax in which I will select * where id='1 , 3' and when I will echo $row[email] it will return
abc#d.com
ah#cc.com
Found the correct syntax:
$all=mysql_query("select * from users where id IN ('1','2','3')");
while($row = mysql_fetch_assoc($all))
{
echo $row['name'];
}
Use IN clause to get records for multiple emails.
$my=mysql_query("select * from users where email IN ('$email','$email2','$email3')")
or die(mysql_error);
Another, not optimal, solution is adding several options to the "where" clause.
Uses more resources, but, sometimes, is what you need.
By the way, I strongly, suggest put you SQL in a variable, first.
$myquery = "select * from users ";
$myquery .= "where (1 = 0) "; // defaults to false
$myquery .= "or (email='$email') "; // maybe true
$myquery .= "or (email='$email2') "; // maybe true
$myquery .= "or (email='$email3') "; // maybe true
$mydataset = mysql_query($myquery) or die(mysql_error);
There multiple "or" expression with a "=" string comparison, are the non optimal, more resources used, equivalent of the "in" operator.
Yet, sometimes is useful to know, or use, this equivalent. If you are not sure if the source string is case sensitive, or you want to trim the value for unwanted spaces, you could also replace the "=" operator by the "like" operator.
$email = trim($email);
$email2 = trim($email2);
$email3 = trim($email3);
$myquery = "select * from users ";
$myquery .= "where (1 = 0) "; // defaults to false
$myquery .= "or (email like '%$email%') "; // maybe true
$myquery .= "or (email like '%$email2%') "; // maybe true
$myquery .= "or (email like '%$email3%') "; // maybe true
$mydataset = mysql_query($myquery) or die(mysql_error);
Cheers.

Pointless SQL vs PHP if

I need to manipulate entries in a mySQL table using code like this
foreach($items as $item)
{
$sql = "UPDATE `siteims` SET refs = refs + 1 WHERE imid = '{$item->img}';";
$sql .= "UPDATE `lists` SET refs = refs + 1 WHERE lid = '{$item->lili}'";
$dbh->exec($sql);
}
There may be as many as 50 items in $items. A variation on this code would be
foreach($items as $item)
{
if ('z' != $img->img)
$sql = "UPDATE `siteims` SET refs = refs + 1 WHERE imid = '{$item->img}';";
if ('z' != $item->lili)
$sql .= "UPDATE `lists` SET refs = refs + 1 WHERE lid = '{$item->lili}'";
$dbh->exec($sql);
}
In both cases I am executing a sequence of SQL statements for EACH item in $items. My questions
Would it not be a whole lot more efficient to build $sql for items and then execute it?
But then if all of the, potentially, 50 items in $items produces meaningful SQL would that not mean a very slowly executing batch of SQL statements?
Finally, is it better to perform PHP side if tests as in the second version of my code or just build the SQL and let mySQL deal with the fact that the WHERE test returns an empty row?
I'd much appreciate any help with this.
You could use an in clause, instead, e.g.
$sql = "UPDATE .... WHERE imid IN (" . implode($array_that_has_the_ids) . ")"
and reduce yourself down to just one single SQL query. However, this can fail if you're trying to use a HUGE aray - the generated query could exceed the max_allowed_packet setting and get killed.
As for your strlen... what's the point of comparing strlen results against 'z'? strlen returns an integer, you might as well be doing if (apple == orange) instead.
At first place I advice you to use IN clause and just 2 separated queries...
You may have to escape those 2 elements $item->img and $item->lili ..
$ids = array("siteims"=>array(), "lists"=>array());
foreach($items as $item)
{
$ids['siteims'][] = "'" . $item->img . "'";
$ids['lists'][] = "'" . $item->lili . "'" ;
}
if(!empty($ids['siteims'])){
$sql = "UPDATE `siteims` SET refs = refs + 1 WHERE imid IN (".implode(',', $ids["siteims"]).")";
$dbh->exec($sql);
}
if(!empty($ids['lists'])){
$sql = "UPDATE `lists` SET refs = refs + 1 WHERE lid IN (".implode(',', $ids["lists"]).")";
$dbh->exec($sql);
}

PHP mysql_query() Select with CONCATENATION

I have the following php code:
mysql_query("SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'");
I also have a string:
$mynumbers = "AND b.question_code IN (1);";
How can I combine this string withing the mysql_query()?
Thanks,
mysql_query("SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."' " . $mynumbers);
But keep in mind that AND GROUP BY all_surveys.question_code IN (1); is incorrect sql and makes no sense.
You can also do like this if you want more simplicity;
$sql="SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'";
$sql.=$mynumbers;
echo $sql;
Also as zerkms said your sql seems to be incorrect
First is, you can not combine above two statements, the alternatively you can do like this-
//Here i assume that you want to concatenate 2nd condition on particular situation so you need to add if condition or else you can directly contcate it with "." (dot) operator.
$query = "SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'";
if(//your condition) $query .= "AND GROUP BY b.question_code IN (1);";
mysql_query($query);
Dont use AND before Group By
Try the following code,
$query = "SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'";
$query .= " GROUP BY b.question_code IN (1)"
mysql_query($query)

Categories