Showing posts with label php problem solutions. Show all posts
Showing posts with label php problem solutions. Show all posts

## Saturday 18 April 2020

### How to check if a number is prime?

Question: What is Prime Number
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.

Question: Give the example of Prime Number
2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

Question: Write an function that check the prime number OR Not?
```function checkPrime(\$number){
if(\$number < 0 ){
return false;
}
\$return=true;
for(\$i=2; \$i < \$number; \$i++){
if(\$number % \$i ==0){
\$return=false;
break;
}
}
return \$return;
}
```

Question: How to check a number is prime Or Not?
```echo checkPrime(2)?'Prime':'Not Prime'; //Prime
echo checkPrime(4)?'Prime':'Not Prime'; //Not Prime
echo checkPrime(6)?'Prime':'Not Prime'; //Not prime
echo checkPrime(7)?'Prime':'Not Prime';  //Prime
```

Question: What are the prime numbers between 1 to 100?
```for( \$i = 2; \$i < 100; \$i++ ){
if( checkPrime( \$i ) ){
echo \$i;
echo ',';
}
}```

## Sunday 29 March 2020

### General error: 1364 Field city_id doesn't have a default value

I have upgraded the MySQL from 5.5 to 5.6 and then getting below type of errors.
General error: 1364 Field 'city_id' doesn't have a default value

(I was not getting such type of error, it must come after upgrading my MySQL Version from 5.5 to 5.6)

### Solution: It have 3 Solutions

1. In Your Code (PHP), always set a default value (if no value) before save.
```\$objSaveData->saveData(
array(
'id'=>111,
'name'=>'New user',
'city_id'=>0, //default value
);
);
```
2. Create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
like below:
```ALTER TABLE `users` CHANGE `city_id` `city_id` INT(10) UNSIGNED NOT NULL DEFAULT '0';
```
3. Disable MySQL Strict Mode (Most appropriate)
Disable it by setting your own SQL_MODE in the my.cnf file, then restart MySQL.

Look for the following line:
`sql-mode = "STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"`
Change it to:
`sql-mode="" `
Restart the MySQL Service.

## Saturday 21 December 2019

### What are special characters? and how to remove special characters?

Question: What are special characters?
Special characters are selected punctuation characters present on standard US keyboard.

Question: Provide list of special characters?
 Character Name Space ! Exclamation " Double quote # Number sign (hash) \$ Dollar sign % Percent & Ampersand ' Single quote ( Left parenthesis ) Right parenthesis * Asterisk + Plus , Comma - Minus . Full stop / Slash : Colon ; Semicolon < Less than = Equal sign > Greater than ? Question mark @ At sign [ Left bracket \ Backslash ] Right bracket ^ Caret _ Underscore ` Grave accent (backtick) { Left brace | Vertical bar } Right brace ~ Tilde

Question: How to remove special characters from string including space?
```\$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-]/', '', \$string);```

Question: How to remove special characters from string except space?
```\$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '', \$string);```

Question: How to replace special characters with hyphen?
```\$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '-', \$string);```

Question: How to replace multiple hyphen with single hyphen?
```\$string='test-----ing';
echo preg_replace('/-+/', '-',\$string);```

Question: How to remove special characters from array?
```\$array=array('test !@#ing','sdalkjsad','#\$#33');
function cleanData(\$string){
return preg_replace('/[^A-Za-z0-9\-]/', '', \$string);
}
\$array = array_map('cleanData',\$array);
print_r(\$array);```

Question: How to remove all special characters from javascript?
```var stringToReplace='test !@#ing';
stringToReplace=stringToReplace.replace(/[^\w\s]/gi, '')```

## Thursday 12 December 2019

### How to resize images in php

Function resizeImage
```
/**
*
* @param type \$width
* @param type \$height
* @param type \$mode
* @param type \$imageName
* @param type \$extension
* @return string
*/
function resizeImage(\$width, \$height, \$mode, \$imageName,\$extension) {
\$docRoot = getenv("DOCUMENT_ROOT");

/* Get original image x y */
\$tmpNM = \$_FILES['files']['tmp_name'];

list(\$w, \$h) = getimagesize(\$_FILES['files']['tmp_name']);
/* calculate new image size with ratio */
\$ratio = max(\$width / \$w, \$height / \$h);
\$h = ceil(\$height / \$ratio);
\$x = (\$w - \$width / \$ratio) / 2;
\$w = ceil(\$width / \$ratio);
/* new file name */
if (\$mode == 'userphoto') {
\$path = \$docRoot . '/upload/userphoto/' . \$imageName;
}

/* read binary data from image file */
\$imgString = file_get_contents(\$_FILES['files']['tmp_name']);
/* create image from string */
\$image = imagecreatefromstring(\$imgString);
\$tmp = imagecreatetruecolor(\$width, \$height);
imagecopyresampled(\$tmp, \$image, 0, 0, \$x, 0, \$width, \$height, \$w, \$h);
\$fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
/* Save image */
\$extension = strtolower(\$extension);
switch (\$extension) {
case 'jpg':
case 'jpeg':
case 'jpe':
imagejpeg(\$tmp, \$path, 100);
break;
case 'png':
imagepng(\$tmp, \$path,0);
break;
case 'gif':
imagegif(\$tmp, \$path, 100);
break;
case 'bmp':
imagewbmp(\$tmp, \$path);
break;
default:

exit;
break;
}
return \$path;
/* cleanup memory */
imagedestroy(\$image);
imagedestroy(\$tmp);
}    ```

How to use Code
HTML Code

```<form action="upload.php" enctype="multipart/form-data" method="post">
<input id="image upload" name="files" type="file" />
<input name="submit" type="submit" value="Upload Image" />

```

PHP Code
```
//List of thumbnails
\$sizes = array(200 => 200, 150 => 150);

\$files=array();
if (!empty(\$_FILES)) {
//Clean the image name
\$_FILES['files']['name'] = preg_replace('/[^a-zA-Z0-9_.-]/', '', strtolower(trim(\$_FILES['files']['name'])));

//Temporary file, type, name
\$tmpNM = \$_FILES['files']['tmp_name'];
\$imageType = \$_FILES['files']['type'];
\$imageName = \$_FILES['files']['name'];

//Get image extension
\$imageNameType = explode(".", \$_FILES['files']['name']);

\$fileMimeTypes = array('image/jpeg', 'image/png', 'image/bmp', 'image/gif'); // mime  extensions
\$fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions

if (in_array(strtolower(\$imageNameType[1]), \$fileTypes)) {
\$fullImageName = time('his') . '_' . \$_FILES['files']['name'];
foreach (\$sizes as \$w => \$h) {
\$files[] = \$this->resizeImage(\$w, \$h, 'userphoto', "{\$w}_{\$fullImageName}", \$imageNameType[1]);
}

}
}```

## Saturday 7 December 2019

### How to Validate email address in PHP?

Following are in built PHP function to validate the email address and Ip Address.

Validate Email - Example 1
```\$email='helo@gmail.com';
if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
echo \$email. ' - Invalid';
}else{
echo \$email. ' - Valid';
}
```

helo@gmail.com - Valid

Validate Email - Example 2
```\$email='464646@gmail.com';
if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
echo \$email. '- Invalid';
}else{
echo \$email. ' - Valid';
}
```

464646@gmail.com - Valid

Validate Email - Example 3
```\$email='arunkumar.com';
if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
echo \$email. ' - Invalid';
}else{
echo \$email. ' - Valid';
}

```

arunkumar.com - Invalid

Validate IP Address - Example 1
Question: How to Validate IP Address?
```\$ipAddress = '127.0.0.1';
}else{
}
```

127.0.0.1 is Valid

Validate IP Address - Example 2
```\$ipAddress = '127.test.0.0.1';
}else{
}
```

127.test.0.0.1 is Valid

Validate URL - Example 1
```\$ipAddress = '127.test.0.0.1';
\$website = 'https://www.web-technology-experts-notes.in';
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",\$website)) {
echo   "Invalid URL";
}else{
echo   "Valid URL";
}
```

Valid URL