0

Create a Zip file with ZipArchive using PHP

ince version 5.2.2 of PHP is available by default native support for compressed archives .zip.

ziparchive-150x150

Let’s see how you can create archives .zip in PHP using the ZipArchive class with very few lines of code. In this example we create a compressed archive of all files within a folder which specify the path:

<?php
$dir="my_dir/";
$files=array();
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if($entry!="." && $entry!=".." )
{
$files[]=basename($entry);
}
}
closedir($handle);
}
$zipname = 'my.zip';
$zip = new ZipArchive();
//Create zip file
$zip->open($zipname, ZIPARCHIVE::CREATE);
if(count($files)>0)
{
foreach ($files as $file) {
//add the files to zip
$zip->addFile($file,$file);
}
//close
$zip->close(); //close
}
?>

0

How to create a table in MySQL in PHP

PhpMyAdmin is undoubtedly the most common tool used to manage and administration of MySQL and that allows for multiple tasks such as creating or modifying databases, tables, records, and more.

Taking this premise we know that many of these operations can be done quickly and with a few clicks, as the case of creating a new table in Db.

In other situations, however, you may have the need to create a table directly from a PHP script semplicemte querying the database with SQL.

As trivial as it may ‘consider a plugin or a module that links its operation in one or more custom tables, that activation by the user (as with many plugins for WordPress), are created in the database used.

We pass in practice and we see a small example, how can create a table in MySQL through PHP and its built-in functions:


<?php
$host="localhost";
$user="root";
$password="password";
$db="database";
$tablename="users";
//connessione al database
$conn=mysqli_connect($host,$user,$password,$db);
/*controllo se è presente una tabella con lo stesso nome */
$res = mysqli_query($conn,"SHOW TABLES LIKE '".$tablename."'");
if(!$res) {
mysqli_query($conn,$sql);
$sql = "CREATE TABLE $tablename (
id int(11) NOT NULL AUTO_INCREMENT, name varchar(30) NOT NULL,
surname varchar(30) NOT NULL,
username varchar(30) NOT NULL,
password varchar(32) NOT NULL,
email varchar(50) NOT NULL,
UNIQUE KEY id (id) );";
$res=mysqli_query($conn,$sql);
if($res) { echo "Tabella creata con successo"; }
}
else {
echo "La tabella esiste nel Db";
}
?>

As shown by the code, once the connection to the database do a first check to see whether or not there is a table in the database called “users“.

If the query result is false you can proceed to the creation of the table.