Merging and Sorting two arrays in PHP

Suppose we have two PHP arrays. Now if we want to merge these two array, then there is a function in PHP to do this. Just use the below code to merge two arrays in PHP.


$combinedArray = array_merge($firstArray, $secondArray);

The above code will return a new combined array of the two arrays.

Now if we want to sort this new array, then :


foreach($combinedArray AS $val) {

$dates[] = strtotime($val['date']);  // here 'date' is the key in our $firstArray and $secondArray and our new array will be sorted according to this.

}

array_multisort($dates, SORT_ASC, $combinedArray);

Note :- Both the arrays $firstArray and $secondArray must have the ‘date’ key, because the new array $combinedArray will be sorted according to this.

Using SQL IN Operator with PHP Array

Using SQL IN operator with PHP array

Suppose we have a array named ‘id_array’ which contains id’s. Now, in order to get all the records from our MySQL table using this array of id, we can use the below given code :


SELECT * FROM TABLE WHERE id IN (".implode(',',$id_array).")

Countdown timer using Javascript

Here is the full javascript tutorial for creating a countdown timer to a certain date. This count down timer contains days, hours, minutes and seconds as well.


// Set the date to which the timer continues

var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();

var x = setInterval(function() {

// Todays date and time

var now = new Date().getTime();

// Distance between now and the countdown date

var distance = countDownDate - now;

var days = Math.floor(distance / (1000 * 60 * 60 * 24));

var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Putting the countdown timer in element with ID demo

document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

// If countdown is over, then putting the text in element with ID demo

if (distance < 0) {

clearInterval(x);

document.getElementById("demo").innerHTML = "EXPIRED";

}

}, 1000);

One more thing to do, just place the below code in your body :


<p id="demo"></p>

Backup MySQL Database Using PHP

Here is the full script to create a backup of your MySQL database using PHP :

backup_tables('localhost','username','password','database');

/* backup the db OR just a table */

function backup_tables($host,$user,$pass,$name,$tables = '*'){

$link = mysql_connect($host,$user,$pass);

mysql_select_db($name,$link);

//get all of the tables

if($tables == '*') {

$tables = array();

$result = mysql_query('SHOW TABLES');

while($row = mysql_fetch_row($result)) {

$tables[] = $row[0];

}

}

else {

$tables = is_array($tables) ? $tables : explode(',',$tables);

}

//cycle through

foreach($tables as $table) {

$result = mysql_query('SELECT * FROM '.$table);

$num_fields = mysql_num_fields($result);

$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));

$return.= "\n\n".$row2[1].";\n\n";

for ($i = 0; $i < $num_fields; $i++) {

while($row = mysql_fetch_row($result)) {

$return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j < $num_fields; $j++) {

$row[$j] = addslashes($row[$j]);

$row[$j] = ereg_replace("\n","\\n",$row[$j]);

if (isset($row[$j])) {

$return.= '"'.$row[$j].'"' ;

}

else {

$return.= '""';

}

if ($j < ($num_fields-1)) {

$return.= ',';

}

}

$return.= ");\n";

}

}

$return.="\n\n\n";

}

//save file

$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');

fwrite($handle,$return);

fclose($handle);

}

How to upload multiple files in CodeIgniter

View : (Save it with name upload.php in your views folder)


<?php echo form_open_multipart('upload/do_upload'); ?>

<?php echo $this->session->userdata('msg');

$this->session->set_userdata('msg', ''); ?>

<input type="file" name="file[]" id="file[]" required multiple="multiple">

<button type="submit" class="btn-input" name="submit" id="submit">Submit</button>

<?php echo form_close(); ?>

Controller : (Save it with name Upload.php in your controller folder)


public function do_upload() {

$filesCount = count($_FILES['file']['name']);

$uploadPath = 'uploads/';   /* uploads folder must be located in your root folder (along with application folder) */

if(!is_dir($uploadPath)) {

mkdir($uploadPath,0755,TRUE);

}

for($i = 0; $i < $filesCount; $i++){

$_FILES['userFile']['name'] = $_FILES['file']['name'][$i];

$_FILES['userFile']['type'] = $_FILES['file']['type'][$i];

$_FILES['userFile']['tmp_name'] = $_FILES['file']['tmp_name'][$i];

$_FILES['userFile']['error'] = $_FILES['file']['error'][$i];

$_FILES['userFile']['size'] = $_FILES['file']['size'][$i];

$config['upload_path'] = $uploadPath;

$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp|doc|pdf|docx|rtf';

$this->load->library('upload', $config);

$this->upload->initialize($config);

if($this->upload->do_upload('userFile')){

$fileData = $this->upload->data();

$uploadData[$i]['file_name'] = $fileData['file_name'];

$uploadData[$i]['created'] = date("Y-m-d H:i:s");

$uploadData[$i]['modified'] = date("Y-m-d H:i:s");

}

}

if(!empty($uploadData)){

$this->session->set_userdata('msg', 'Files Uploaded Successfully');

$this->session->set_userdata('status', 'success');

$this->load->view('upload', $uploadData);

}

else {

$this->session->set_userdata('msg', $this->upload->display_errors());

$this->session->set_userdata('status', 'fail');

$this->load->view('upload');

}

 

How to send email with an attachment in PHP using PHPMailer

Firstly, download the PHPMailer library from the given link :

https://github.com/PHPMailer/PHPMailer

Now extract the zip folder and rename it to ‘PHPMailer’ and place it in your root folder where all the php files are located.

Then after put this code :


require_once('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = ''; /* put the email from which the email is to be sent */
$mail->FromName = ''; /* put the name of a person who is sending email */
$mail->Subject = ''; /* give a subject of email if you want */
$message_body = "Hello, sending mail using PHPMailer";
$mail->Body = $MESSAGE_BODY;
$mail->AddAddress( '' ); /* put the email of the recipient */

$mail->AddAttachment('PATHTOFILE'); /* put the path to the file */

if ($mail->Send())
{
echo "Mail Sent";
}
else
{
echo "Could not send mail";
}