Saturday, 27 June 2015

PHP: error_log

(PHP 4, PHP 5) error_log — Send an error message to the defined error handling routines Description bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] ) Sends an error message to the web server's error log or to a file. Parameters message The error message that should be logged. message_type Says where the error should go. The possible message types are as follows: error_log() log types 0 ...

PHP: Generate CSV from mysql and email out

<?php //mysql user variables $mysqli = new mysqli("localhost", "user", "password", "database"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } //grab all rows from the table where state is "new" and put into array $query = "SELECT Field1,Field2"; //loop the fetch and concactenate into string if ($result = $mysqli->query($query)) { $data[] = array('Field1','Field2'); while ($row = $result->fetch_assoc()) { $data[] = array($row['Field1'],$row['Field2']); ...

PHP: Converts enum fields from mysql into an array

enumExplode.php <?php function enumExplode($tableCol) {     $expl = explode(".", $tableCol);     $table = $expl[0];     $column = $expl[1];     $query = "show columns from {$table} where field = :column";     $res = querydb($query, array("column" => $column), $error);     $enum = $res[0]['Type'];     $enum = explode(",", str_replace(array("enum(", ")", "'"), "", $enum));     return $error ?: $enum; } /**  *  queryDB  *  -------  * ...

Mysql: Mass Find and Replace MySQL

<?php /* * MySQL Mass Find and Replace */ // Connect to your MySQL database. $hostname = "localhost"; $username = "root"; $password = "password"; $database = "db_name"; mysql_connect($hostname, $username, $password); // The find and replace strings. $find = "what_i_need_to_find"; $replace = "what_i_need_to_replace_with"; // Test mode $test_mode = false; // Loop through all tables and columns $loop = mysql_query(" SELECT concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,',...

Mysql: Back up mysql databases

<?php // dump mysql file $myUser = 'root'; $myPass = 'root'; $myHost = 'localhost'; $myDbs  = array('db1', 'db2'); $destDir = './backup/'; $date = date('Ymd'); $files = array(); foreach ($myDbs as $v) {  $file = $destDir.$v.'-'.$date.'.sql.gz';  $files[] = $file;  exec("/usr/bin/mysqldump -u $myUser -h $myHost -p$myPass --opt $v | /bin/gzip -9 > $file"); } ?> ...

Mysql: Transaction with php+mysql

<?php mysql_connect("localhost", "test_user", "test_password"); mysql_select_db("work"); //transaction begin mysql_query("BEGIN"); $sorgu1 = mysql_query("UPDATE test SET mevcut_para = mevcut_para – 10000 WHERE hesap_no = '625021'"); $sorgu2 = mysql_query("UPDATE test1 SET mevcut_para = mevcut_para + 10000 WHERE hesap_no = '124500'"); if (!$sorgu1 or !$sorgu2 ){ mysql_query("ROLLBACK"); }else{ mysql_query("COMMIT"); } ?>...

PHP : Session handler via mySQL

<?php class MySQLSessionHandler { private $_dblink; private $_sessionName; private $_sessionTable; CONST SESS_EXPIRE = 3600; public function __construct($host, $user, $pswd, $db, $sessionName, $sessionTable) { $this->_dblink = new mysqli($host, $user, $pswd, $db); $this->_sessionName = $sessionName; $this->_sessionTable = $sessionTable; session_set_save_handler( array($this, "session_open"), array($this, "session_close"), ...

PHP: Script to import json to mysql in php

<?php  $content = json_decode(file_get_contents("filename.json")), true); mysql_connect('localhost', 'user', 'pass'); mysql_select_db('db');  foreach($content as $item) { $columns = implode(", ",array_keys($item)); $escaped_values = array_map('mysql_real_escape_string', array_values($item)); $values = "'".implode("', '", $escaped_values)."'"; $sql = "INSERT INTO `tbl_name`($columns) VALUES ($values)"; mysql_query($sql); }   ?> ...

PHP: Patch mysql injection

<?php $patch_array = array($_GET['id'],$_GET['page']); foreach ($patch_array as $key) { $patch_getter = $key; $patch_1 = ereg("-", $patch_getter); $patch_2 = ereg("order", $patch_getter); $patch_3 = ereg("_", $patch_getter); $patch_4 = ereg("concat", $patch_getter); $patch_5 = ereg("concat/*!()*/", $patch_getter); $patch_6 = ereg("/*!concat()*/", $patch_getter); $patch_7 = ereg("%20order%20", $patch_getter); $patch_8 = ereg("/*!00000uNiOn*/+/*!00000sElEcT*/", $patch_getter); $patch_9 = ereg("\*order\*",...

PHP: Script to show all tables in a MySQL schema

<?php //open database connection $mysqli = new mysqli(<host>,<username>,<password>,<schema>);   //Display error message if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); }   $sql="SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = <schema name>"; $result=$mysqli->query($sql); while ( $tables = $result->fetch_assoc()) { echo "<br>".$tables['TABLE_NAME']; } // Free memory by clearing...

Mysql: Backup Your MySQL Database Using PHP

<?php // Backup Your MySQL Database Using PHP // ------------------------------------ // Use : backup_tables('localhost','username','password','blog'); // ( - 5th param would be the tables, empty or * will get all the complete db. ) /* 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...

Mysql: How convert mysql date in php, back and foward

Dates in PHP and MySQL I see a lot of people on forums and on my training courses asking about the best way (or any way) to manage dates stored in a MySQL database and used in PHP. Three options follow, but first the problem. PHP uses unix timestamps for all its date functionality. It has methods to convert these timestamps into pretty much any text format you could want but internally it uses the timestamp format. A timestamp is simply an integer. Specifically, it's the number of seconds that have elapsed since midnight on January...

importing csv file into mysql using php

<?php define("DB_HOST", "localhost"); define("DB_NAME", "db_name"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("CSV_FILE", "file.csv"); $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "," . DB_USER . "," . DB_PASSWORD); if (($handle = fopen(CSV_FILE, "r")) !== FALSE) { ...

Check MySQL db connection in php

<?php /** * Checking the MySQL connection */ // Host name $host = "localhost"; // MySQL username $username = "databaseusername"; // MySQL password $password = "password"; // MySQL database name $databasename = "dbname"; echo "Checking connection with {$host}<br/>"; // ------------------------------ // Connect to mysql with the host, username, password // ------------------------------ $con = mysql_connect($host,$username,$password); if (!$con) { die('Could not...

Convert mysql UTC timestamp to Local timestamp PHP

function convert_time($timestamp,$timezone) { date_default_timezone_set("UTC"); $time_object = new DateTime($timestamp, new DateTimeZone('UTC')); $time_object->setTimezone(new DateTimeZone($timezone)); return $time_object->format('Y-m-d g:i A'); } ...

mysql dump query to json on php

<?php mysql_connect('localhost','user','password'); mysql_select_db('database'); $query = ""; $sth = mysql_query($query); $rows = array(); while($r = mysql_fetch_assoc($sth)) { $rows[] = $r; } print json_encode($rows); ?> ...

Export MySQL table in CSV format using PHP

<?php $link = mysql_connect($mysql_host,$mysql_user,$mysql_pass) or die('Could not connect: '.mysql_error()); mysql_select_db($mysql_db,$link) or die('Could not select database: '.$mysql_db); $query = "SELECT * FROM $tablename ORDER BY id"; $result = mysql_query($query) or die("Error executing query: ".mysql_error()); $row = mysql_fetch_assoc($result); $line = ""; $comma = ""; foreach($row as $name => $value) { $line .= $comma . '"' . str_replace('"', '""', $name) . '"'; $comma = ";"; } $line .= "\n"; $out...

Export mySQL databases via PHP

<?php //In the event that PHP / mySQL is set up funkily. error_reporting(E_ALL & ~(E_STRICT|E_NOTICE|E_DEPRECATED)); ini_set('display_errors', '1'); //Fill these in. $host = ''; $username = ''; $password = ''; $database = ''; //Taken from http://davidwalsh.name/backup-mysql-database-php backup_tables($host,$username,$password,$database); function backup_tables($host,$user,$pass,$name,$tables = '*') { $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //get...