
In this post you can see 5 BAD practices used by many PHP programmers and their correct alternative.
1. Do not hardcode widely used strings
(put them all in the config file)
Bad practice:
mailExample.php
================
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user';
$mail->Password = 'password';
$mail->AddReplyTo('contact@example.com', 'Support Team');
$mail->AddAddress($email, "{$firstname} {$lastname}");
$mail->SetFrom('contact@example.com', 'Support Team');
$mail->Subject = "Email subject";
$mail->AltBody = '';
$mail->Body = $txt_body;
if ($mail->Send()) {
//Do something
}
================
Good practice:
config.php
================
define('SMTP_HOST', 'smtp.example.com');
define('SMTP_USERNAME', 'user');
define('SMTP_PASSWORD', 'password');
define('SMTP_EMAIL_FROM', 'contact@example.com');
define('SMTP_EMAIL_FROM_NAME', 'Support Team');
================
mailExample.php
================
require_once('config.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = SMTP_HOST;
$mail->SMTPAuth = true;
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->AddReplyTo(SMTP_EMAIL_FROM, SMTP_EMAIL_FROM_NAME);
$mail->AddAddress($email, "{$firstname} {$lastname}");
$mail->SetFrom(SMTP_EMAIL_FROM, SMTP_EMAIL_FROM_NAME);
$mail->Subject = "Email subject";
$mail->AltBody = '';
$mail->Body = $txt_body;
if ($mail->Send()) {
//Do something
}
================
2. Avoid running MySQL "select" queries inside loops
(Select all the rows in one query and then build the needed array with PHP)
Bad practice:
example.php
================
$finalResult = array();
$categories = mysql_query("SELECT * FROM `tbl_categories`;");
while ($category = mysql_fetch_array($categories, MYSQL_ASSOC)) {
$categoryProducts = mysql_query("SELECT * FROM `tbl_products` WHERE `category_id` = '".$category['id']."';");
while ($product = mysql_fetch_array($categoryProducts, MYSQL_ASSOC)) {
$finalResult[$category['id']][$product['id']] = $product['name'].' ('.$category['name'].')';
}
}
================
Good practice:
example.php
================
$finalResult = array();
$result = mysql_query(
"SELECT
`c`.`id` AS `category_id`, `c`.`name` AS `category_name`,
`p`.`id` AS `product_id`, `p`.`name` AS `product_name`
FROM `tbl_categories` AS `c`
JOIN `tbl_products` AS `p`
ON `p`.`category_id` = `c`.`id`;
");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$finalResult[$row['category_id']][$row['product_id']] = $row['product_name'].' ('.$row['category_name'].')';
}
================
3. Don't overuse the server resources
(Optimize your code and execute every part of it only when it's necessary)
Bad practice:
example.php
================
$getCategories = (bool)$_GET['categories'];
$categories = mysql_query(/*Very heavy SQL query*/);
if ($getCategories) {
while ($category = mysql_fetch_array($categories, MYSQL_ASSOC)) {
//Some logic
}
}
================
Good practice:
example.php
================
$getCategories = (bool)$_GET['categories'];
if ($getCategories) {
$categories = mysql_query(/*Very heavy SQL query*/);
while ($category = mysql_fetch_array($categories, MYSQL_ASSOC)) {
//Some logic
}
}
================
4. Don't invent your own coding style
(Keep the standards: indents, spaces, naming, comments)
Bad practice:
example.php
================
function gpi($pi, $ct = 'image')
{
if (isset($pi)){
$pif = '';
switch ($ct) {
case 'image' : {
// Some code
break;
}
case 'text' : {
// Some code
break;
}
default : {
// Some code
break;
}
}
return $pif;
} else {
return false;
}
}
================
Good practice:
example.php
================
/**
* This function will get from database the description of a needed
* product and will return the formatted version of it
* in dependence of the $contentType.
*
* @param $productId The ID of the product
* @param string $contentType The content type
* @return bool|string In case the function is called wrong it will return false, otherwise - product description
*/
function getProductInfo($productId, $contentType = 'image') {
if (isset($productId)){
$productInfo = '';
switch ($contentType) {
case 'image' : {
// Some code
break;
}
case 'text' : {
// Some code
break;
}
default : {
// Some code
break;
}
}
return $productInfo;
} else {
return false;
}
}
================
5. Don't mix different types of logic
(Split your logic following the MVC architecture)
Don't write your PHP/MySQL, HTML, CSS and JavaScript code in the same file. Each of these should be split into different files. Also the PHP files should be split at least into 2 parts: the database controller part which executes MySQL queries and the logical part.
No comments:
Post a Comment