Visualizzazione post con etichetta php. Mostra tutti i post
Visualizzazione post con etichetta php. Mostra tutti i post

Php MySQl duplicare un record di una tabell con un solo comando

Comando molto utile per duplicare con 3 righe di codice un record presente nella nostra tabella prodotti.

include ("confDB.php");
$db = @mysql_select_db($db_nome, $connessione) or die("Impossibile selezionare il database.");
##########inserimento####################
$est="Duplicato"; $prodotto=$_GET['id_pro'];
$sql = "insert into prodotti (m_categoria, categoria, marca, nome,fila, posto, codice)
SELECT m_categoria, categoria, marca, nome, fila, posto, codice FROM prodotti WHERE id_pro = \"$prodotto\" order by id_pro desc limit 0,1
";

$risultato = @mysql_query($sql,$connessione)
        or die("Impossibile eseguire l'interrogazione su catture.");

volendo aggiungere qualcosa possiamo richiamare l'ultimo prodotto inserito, quindi il mio duplicato, e modificare il titolo aggiungendo al nome il prefisso: Duplicato

Php: creare una copia del DataBase MySql e cancellazione della vecchia copia

Ecco uno script in php che esegue la copia del nostro DataBase MySql
cancella le copie precedenti usando filemtime di php
ed invia una mail
se poi ci mettete un cronjob che avvia il tutto alle 2 di notte il gioco è fatto:

error_reporting(E_ALL);

/* Define database parameters here */
define("DB_USER", 'tuo user');
define("DB_PASSWORD", 'tua pass');
define("DB_NAME", 'nome db');
define("DB_HOST", 'host');
define("OUTPUT_DIR", 'dbBackup'); // Folder / Directory Name
define("TABLES", '*');

/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status . "";
##############################################################################
$destinatario="tua mail";

$email="$email";
$web="www.tuosito.it";
$Da="From: $email";
$sitename = "Nome sito";
$oggetto="Copiato DB";
$info="Data base copiato con successo";

            $headers .= "From: $sitename <$destinatario>\n";
$headers .= "Reply-To: $destinatario <$destinatario>\n";

mail($destinatario,$oggetto,$info,$headers);

##############################################################################
/* The Backup_Database class */

class Backup_Database {
/* Host where database is located  */

  var $host = 'localhost';
  var $username = 'root';
  var $passwd = '';
  var $dbName = 'YOUR_DATABASE _NAME';
  var $charset = '';

  /* Constructor initializes database */

  function Backup_Database($host, $username, $passwd, $dbName, $charset = 'utf8') {
    $this->host = $host;
    $this->username = $username;
    $this->passwd = $passwd;
    $this->dbName = $dbName;
    $this->charset = $charset;
    $this->initializeDatabase();
  }

  protected function initializeDatabase() {
    $conn = @mysql_connect($this->host, $this->username, $this->passwd); // Ik Added @ to Hide PDO Error Message
    mysql_select_db($this->dbName, $conn);
    if (!mysql_set_charset($this->charset, $conn)) {
      mysql_query('SET NAMES ' . $this->charset);
    }
  }

  /* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' @param string $tables  */

  public function backupTables($tables = '*', $outputDir = '.') {
    try {
      /* Tables to export  */
      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);
      }

      $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
      $sql .= 'USE ' . $this->dbName . ";\n\n";

  /* Iterate tables */
  foreach ($tables as $table) {
    echo "Backing up " . $table . " table...";

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

    $sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
    $sql.= "\n\n" . $row2[1] . ";\n\n";

    for ($i = 0; $i < $numFields; $i++) {
      while ($row = mysql_fetch_row($result)) {
        $sql .= 'INSERT INTO ' . $table . ' VALUES(';
        for ($j = 0; $j < $numFields; $j++) {
          $row[$j] = addslashes($row[$j]);
          // $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
          if (isset($row[$j])) {
            $sql .= '"' . $row[$j] . '"';
          } else {
            $sql.= '""';
          }
          if ($j < ($numFields - 1)) {
            $sql .= ',';
          }
        }
        $sql.= ");\n";
      }
    }
    $sql.="\n\n\n";
    echo " OK

" . "";
  }
} catch (Exception $e) {
  var_dump($e->getMessage());
  return false;
 }

    return $this->saveFile($sql, $outputDir);
  }

  /* Save SQL to file @param string $sql */

  protected function saveFile(&$sql, $outputDir = '.') {
    if (!$sql)
      return false;

    try {
      $handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
      fwrite($handle, $sql);
      fclose($handle);
    } catch (Exception $e) {
      var_dump($e->getMessage());
      return false;
    }
    return true;
  }

}
?>
##########qui puliamo la cartella dalle vecchie copie impostando la variabile data_o#
if ($handle = opendir('./dbBackup')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
$filename = "$entry";
#$data_file=date("Y-m-d", filemtime($filename));
            echo "$filename $entry $data_file
";
$ultima_modifica = date ('Y-m-d', filemtime("./dbBackup/$filename"));
echo 'Ultima modifica al file pagina.php: '  . $ultima_modifica."
";
$data_o=date ("Y-m-d",mktime(date("H"),date("i"),0,date("m"),date("d"),date("Y")));
if($data_o!="$ultima_modifica"){unlink("./dbBackup/$filename");}
        }
    }
    closedir($handle);
}
?>

Potete processare il tutto alle 2 di notte lanciando un spider o un cronjob

Ricavare le lettere dell'alfabeto con una funzioncina di php

utile per scremare una lista di prodotti e/o notizie:

echo"Riduci per:";
foreach (range('A', 'Z') as $letter)
   echo"$letter - ";
?>

Estrarre la data di nascita dei clienti per auguri di compleanno

Ottima strategia di e-mail marketing quella di memorizzare per poi visualizzare le date di compleanno dei clienti. Con una piccola applicazione in php possiamo visualizzare i clienti che compiono gli anni oggi e nei prossimi 5 giorni. Clienti a cui possiamo mandare dei semplici auguri o gli auguri e delle offerte particolari se hanno scelto di ricevere delle promozioni dal nostro sito.
Vedia la funzione php:
- faccio la connessione al mio db
- mi creo la query per oggi e i 5 giorni successivi quindi:

for($d=0; $d<5;>
$data=date("m-d",mktime(date("H"),date("i")-15,0,date("m"),date("d")+"$d",date("Y")));##la data di oggi che si incrementa grazie al for###
$sql = "SELECT *
FROM utenti WHERE data LIKE '%$data%' ORDER BY id_ute DESC
";
##########visualizzo###########################################
$risultato = @mysql_query($sql,$connessione)
or die("Impossibile eseguire l'interrogazione.");


while ($riga = mysql_fetch_array($risultato)) {
$id_ute= $riga['id_ute'];
$nome = $riga['nome'];
$cognome = $riga['cognome'];
$data = $riga['data'];
$off = $riga['off'];####qui vedo se il cliente ha scelto di ricevere delle offerte##
$data = explode("-",$data);
if (in_array("$cognome $nome", $utente)){###questo mi permette di scartare i clienti ripetuti###
}else{
echo"
$cognome $nome
$data[2]/$data[1]/$data[0]
$off
<#a href=\"mostra_utente.php&id_ute=$id_ute\"#>Visualizza<#/a#>
";
}
$utente[ ]="$cognome $nome";###riempio l'array per controllare se ho cliente ripetuti##
}
#########fine visualizzo#######################
}

Utile se si vuole fare una campagna email marketing molto accurata. Nella scheda cliente si potrebbe avere già una mail pronta con gli auguri dove aggiungere i prodotti + visti dal cliente, ma non acquistati, ad un prezzo promozionale.

Individuare e visualizzare file in cartella

Semplice script per individuare i file presenti in una cartella precisa del vostro sito web. Se immagini le visualizziamo:

$cartella = opendir('../img_news'); ###la vostra cartella#########
while ($file = readdir($cartella)) {
if ( $file == ".." || $file == ".") {
}else{
echo"<\img src=../img_news/$file>
###qui visualizzo###

http://www.tuosito.com/img_news/$file



";
}

}

Script utile se si vuole avere l'elenco dei file presenti in una cartella

Thumbnail al volo con php

Script veloce, veloce che ci permette di ridimensionare le img inseriti nel nostro sito con misura impostata nell'url dell'img:
########inizio codice###########
if (!isset($image)){ // if not generate an error image
$img = ImageCreate(100, 100);
$red = ImageColorAllocate($img, 255, 0, 0);
$yellow = ImageColorAllocate($img, 255, 255, 0);
ImageString($img, 5, 20, 20, "Bad", $yellow);
ImageString($img, 5, 20, 40, "size", $yellow);
ImageString($img, 5, 20, 60, "given!", $yellow);
ImagePNG($img);
ImageDestroy($img);
exit();
}

// attempt to load the big image
if (!$bigimage = @ImageCreateFromJPEG($image)) { // if loading fails
$img = ImageCreate(80, 80); // generate an error
$red = ImageColorAllocate($img, 255, 0, 0); // image
$yellow = ImageColorAllocate($img, 255, 255, 0);
ImageString($img, 5, 20, 20, "Image", $yellow);
ImageString($img, 5, 20, 40, "not", $yellow);
ImageString($img, 5, 20, 60, "found!", $yellow);
ImagePNG($img);
ImageDestroy($img);
exit();
}

// all seems to be OK so start the processing
// create the new image using the tnsize parameter
$tnimage = imagecreatetruecolor($tnsize, $tnsize);
// allocate the background colour for the thumbnail
$darkblue = imagecolorallocatealpha($tnimage, 0, 0, 127);
// set the background as transparent
imagecopyresampled($tnimage,$darkblue);
imagefilledrectangle($tnimage, 0, 0, $destW, $destH, $darkblue);
// get the parameters of the big image
$sz = GetImageSize($image);
// load our internal variables
$x = $sz[0]; // big image width
$y = $sz[1]; // big image height
// find the larger dimension
if ($x>$y) { // if it is the width then
$dx = 0; // the left side of the new image
$w = $tnsize; // the width of the new image
$h = ($y / $x) * $tnsize; // the height of the new image
$dy = 0; // the top of the new image
}else{ // if the height is larger then
$dy = 0; // the top of the new image
$h = $tnsize; // the height of the new image
$w = ($x / $y) * $tnsize; // the width of the new image
$dx = 0; // the left edgeof the new image
}
if ($w>$h) {
$tnimage = imagecreatetruecolor($w, $h);
}else{
$tnimage = imagecreatetruecolor($w, $h);
}
// copy the resized version into the thumbnal image
imageCopyResampled($tnimage, $bigimage, $dx, $dy, 0, 0, $w, $h, $x, $y);
// generate the PNG image
ImagePNG($tnimage);
// release the memory used by the thumbnail image
ImageDestroy($tnimage);
// release the memory used by the original big image
ImageDestroy($bigimage);
// all done!
####fine cod#########################

l'immagine la richiamiamo così:
img src="tnp.php?big.jpg&tnsize=150" dove tnp.php è il file dove metteremo il codice sopra riportato sopra. e la var tnsize e la misura max che vogliamo dare alla nostra img.
Utilissimo

Un server per php, in locale

Questo post lo dedichiamo a chi decide di avvicinarsi al php e mysql, e per questo necessita di un server dove poter testare i propri script, magari quelli che ha trovato nel nostro blog.
Per fare questo non serve, almeno per l'inizio, uno spazio web on-line...basta installare easyphp, un programma, in italiano, che con dei semplice click ci permetterà di trasformare il nostro computer un vero e proprio server, con quasi tutte le estensioni php, mysql ed altro....
Qui il link per EasyPhp

Explode date, ottenere giorno mese ed anno da date. PHP

Un piccolo explode per ottenere giorno, mese ed anno dal campo date così strutturato: gg-mm-aaaa

la data di oggi:
$data_o_v=date ("Y-m-d",mktime(date("H"),date("i")-15,0,date("m"),date("d"),date("Y")));
mi da: 2009-05-05
mi tiro fuori i campi:

$data_o=explode("-", $data_o_v); #uso la variabile data_o perchè data_o_v mi potrebbe riservire#
quindi ho:
echo"$data_o[2]/$data_o[1]/$data_o[0]"; -> 05/05/2009

Convertire caratteri speciali, php

Come togliere i caratteri speciali e spesso e volentieri invisibili che disturbano il nostro codice:

$pippo= str_replace("\n","", $pippo);
$pippo = str_replace("\r","", $pippo);
$pippo = str_replace("\t","", $pippo);

Codice che risolverà il dannoso problemi degli spazi invisibili

Visualizzare file esterni con safe_mode abilitato, script php

Capita più spesso che i server in cui girano i nostri siti siano protetti dalla modalità safe_mode abilitata. A capita sempre più spesso che ci sia utile l'accesso a file esterni, come file xml. Di seguito un utile script che visualizza sul nostro sito la pagina di www.php.net

#usage:
$r = new HTTPRequest('http://www.php.net');
echo $r->DownloadToString();
class HTTPRequest
{
var $_fp; // HTTP socket
var $_url; // full URL
var $_host; // HTTP host
var $_protocol; // protocol (HTTP/HTTPS)
var $_uri; // request URI
var $_port; // port
// scan url
function _scan_url()
{
$req = $this->_url;
$pos = strpos($req, '://');
$this->_protocol = strtolower(substr($req, 0, $pos));
$req = substr($req, $pos+3);
$pos = strpos($req, '/');
if($pos === false)
$pos = strlen($req);
$host = substr($req, 0, $pos);
if(strpos($host, ':') !== false)
{
list($this->_host, $this->_port) = explode(':', $host);
}
else
{
$this->_host = $host;
$this->_port = ($this->_protocol == 'https') ? 443 : 80;
}
$this->_uri = substr($req, $pos);
if($this->_uri == '')
$this->_uri = '/';
}
// constructor
function HTTPRequest($url)
{
$this->_url = $url;
$this->_scan_url();
}
// download URL to string
function DownloadToString()
{
$crlf = "\r\n";
// generate request
$req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
. 'Host: ' . $this->_host . $crlf
. $crlf;
// fetch
$this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
fwrite($this->_fp, $req);
while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
$response .= fread($this->_fp, 1024);
fclose($this->_fp);
// split header and body
$pos = strpos($response, $crlf . $crlf);
if($pos === false)
return($response);
$header = substr($response, 0, $pos);
$body = substr($response, $pos + 2 * strlen($crlf));
// parse headers
$headers = array();
$lines = explode($crlf, $header);
foreach($lines as $line)
if(($pos = strpos($line, ':')) !== false)
$headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
// redirection?
if(isset($headers['location']))
{
$http = new HTTPRequest($headers['location']);
return($http->DownloadToString($http));
}
else
{
return($body);
}
}
}
?>

Da provare, senza abusare

Number_format per l'euro €

Il comando number_format nasce per il dollaro e/o sterlina, quindi per l'euro, in visualizzazione, possiamo avere dei problemi. Vediamo come risolverli:

Abbiamo il nostri prezzi:
$prezzo1="550.50";
###il . è fondamentale per la somma,senza . non si somma con il prezzo2###
$prezzo2="550.30";
con una semplice somma avremo:
$totale=$prezzo1+$prezzo2;
e avremo in visualizzazione: 1100.80

risultato che non è corretto per l'euro, si richiede la , per i decimali e il .
ecco number_format che ci aiuta:

$totale=number_format($totale, 2, ',', ' '); ##visualizza 2 decimali divisi da , e le migliaia divisi da spazio###
$totale=str_replace(" ",".",$totale); ###trasformo lo spazio in .####
quindi in visualizzazione avrò: 1.100,80

N.B: il valore creato è solo un valore di visualizzazione, per sommarlo dovremo sempre lavorare con il totale creato senza number_format

Un text editor per siti web in java

Potentissimo editor in java per il proprio sito web, compatibile con tutti i browser. Ricco di applicazioni, può essere integrato più o meno facilmente con php ed asp. Gli esempi disponibili vanno modificati perchè il form comunica solo una variabile generica.
Per visualizzare e memorizzare la nostra variabile nel db basta richiamare: $FCKeditor1

Per togliere i vari pulsanti, basta andare sul file fckconfing.js e togliere i parametri presenti nell'array: FCKConfig.ToolbarSets. La cosa fondamentale sarà controllare che l'array non si concluda con "virgola".
E' possibile scaricare l'editor qui >>