When you have a long fields in SQL query, how do you make it more readable?
For example:
public function findSomethingByFieldNameId($Id) {
$sql = "SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
FROM table
JOIN table2 AS TNS ON TNS.id = table.id
WHERE something = 1";
return $this->db->fetchData($sql, null, 'all');
}
It is more efficient to do this in PHP. Faster depends on the machines involved, if you're talking about faster for one user. If you're talking about faster for a million users hitting a website, then it's more efficient to do these calculations in PHP.
You can use php/mssql extensions .
php $connect=mysql_connect('localhost', 'root', 'password'); mysql_select_db("name"); //here u select the data you want to retrieve from the db $query="select * from tablename"; $result= mysql_query($query); //here you check to see if any data has been found and you define the width of the table If($result){ echo "< ...
MySQL provides a LIMIT clause that is used to specify the number of records to return. The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables.
I prefer Heredoc syntax, though Nowdoc would also work for your example:
Heredoc:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Nowdoc: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
The advantage with both is you can copy and paste straight SQL to and from this block without having to escape or format it. If you needed to include parsing, such as you would do with variables from a double-quoted string, you'd use Heredoc. Nowdoc behaves like single-quotes.
Nowdoc:
public function findSomethingByFieldNameId($Id) {
$sql = <<<'SQL'
SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
FROM table
JOIN table2 AS TNS ON TNS.id = table.id
WHERE something = 1
SQL;
return $this->db->fetchData($sql, null, 'all');
}
Heredoc:
public function findSomethingByFieldNameId($Id) {
$sql = <<<SQL
SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
FROM table
JOIN table2 AS TNS ON TNS.id = table.id
WHERE something = '$Id'
SQL;
$sql = mysql_real_escape_string($sql);
return $this->db->fetchData($sql, null, 'all');
}
You can concatenate it like this to make it more readable:
$sql = "SELECT field1, field2, field3 as Field3_Something,";
$sql.= " field4, field5, field6, field7, field8, field9";
$sql.= " FROM table JOIN table2 AS TNS ON TNS.id = table.id";
$sql.= " WHERE something = 1";
Note: Be sure while concatinating your query, don't forget to leave spaces before you start a new line between your double quotes, else you'll get query invalid error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With