Showing posts with label PHP ob_start. Show all posts
Showing posts with label PHP ob_start. Show all posts

Tuesday, 2 June 2015

Mysql: create a simple input / update query to mysql

<?php 
  session_start
(); 
  if (!
ob_start("ob_gzhandler")) 
      
ob_start(); 
  
header("Expires: Mon, 26 Jul 1997 03:00:00 GMT"); 
  
header("Cache-Control: no-cache"); 
  
header("Pragma: no-cache"); 

  
//  url to host 
  
$url "localhost"; 
  
// database user 
  
$dbuser "Your dbuser name"; 
  
//  database user's password 
  
$pwrd "dbuser password"; 

  
//  Show the information_schema 
  
$show_information_schema 1; 

  
$con mysql_connect($url$dbuser$pwrd) or die(mysql_error()); 
  
mysql_set_charset("utf8"$con); ?> 
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript">
function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
     objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
     objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
         document.getElementById("txtResult").innerHTML= xmlHttp.responseText;
}
else {
         //alert(xmlHttp.status);
}
}

// Will populate data based on input
function htmlData(url, qStr)
{
if (url.length==0)
{
     document.getElementById("txtResult").innerHTML="";
     return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
     alert ('Please use a browser that support "HTTP Request"');
     return;
}

url=url+"?"+qStr;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true) ;
xmlHttp.send(null);
}
</script>
</head>
<body>
<?php 
  
//  ##############  # FUNCTION START  #  ############## 

  
function get_db($con) 
    { 
      
$i 0; 
      
$res = array(); 

      
$db_list mysql_list_dbs($con); 

      
$cnt mysql_num_rows($db_list); 
      while (
$i $cnt) 
        { 
          
array_push($resmysql_db_name($db_list$i)); 
          
$i++; 
        } 
      if (
count($res) >= 1) 
        { 
          
array_unshift($res"Select database"); 
          return 
$res; 
        } 
      else 
          return array(
" No tables :-( "); 
    } 
  
//  --------------  - 

  
function desc_table($use_table$con) 
    { 
      
$sql "desc $use_table"; 
      
$result mysql_query($sql$con); 

      if (!
is_object($result) && !$result == false) 
        { 
          
$array = array(); 
          while (
$ar mysql_fetch_assoc($result)) 
            { 
              
$tmp[0] = $ar['Field']; 
              
$tmp[1] = $ar['Type']; 
              
array_push($array$tmp); 
            } 
        } 
      return 
$array; 
    } 

  
//  --------------  - 
  
function sql_insert($array$use_table) 
    { 
      
$sql_value ""; 
      
$sql_str "\$sql_query = \"INSERT INTO " $use_table " ("; 

      foreach (
$array as $key => $value) 
        { 
          
$sql_str .= $value[0] . ", "; 
        } 

      
$sql_str substr_replace($sql_str"", -2) . " )VALUES ("; 

      foreach (
$array as $key => $value) 
        { 
          switch (
substr($value[1], 04)) 
            { 
              case 
"char": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"date": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"int(": 
                  
$sql_value .= ' $' $value[0] . ' ,'; 
                  break; 
              case 
"text": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"date": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"tiny": 
                  
$sql_value .= ' $' $value[0] . ' ,'; 
                  break; 
              case 
"varc": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
            } 
        } 

      
$sql_str .= substr_replace($sql_value"", -2) . " )"; 

      return 
$sql_str '";'; 
    } 

  
//  --------------  - 

  
function sql_update($array$use_table) 
    { 
      
$sql_str "\$sql_query = 'UPDATE " $use_table " SET "; 

      foreach (
$array as $key => $value) 
        { 
          switch (
substr($value[1], 04)) 
            { 
              case 
"char": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'" ,'; 
                  break; 
              case 
"date": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"int(": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"text": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'", '; 
                  break; 
              case 
"time": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"tiny": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"varc": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'", '; 
                  break; 
            } 
        } 

      return 
substr_replace($sql_str"", -2) . " WHERE "; 
    } 

  
//  --------------  - 

  
function get_tables($con$dbname) 
    { 
      
$sql "SHOW TABLES FROM $dbname"; 
      
$result mysql_query($sql); 
      
$res = array(); 
      if (!
$result) 
        { 
          echo 
"DB Error, could not list tables\n"; 
          echo 
'MySQL Error: ' mysql_error(); 
          die; 
        } 

      while (
$row mysql_fetch_row($result)) 
        { 
          
array_push($res$row[0]); 
        } 
      
array_unshift($res"Select table"); 
      return 
$res; 
    } 

  
//  --------------  - 

  
function create_post_var($ar) 
    { 
      foreach (
$ar as $k => $v) 
        { 
          echo 
'$' $v[0] . ' = mysql_real_escape_string($_POST[' "'$v[0]'" ']);<br>'; 
        } 
    } 

  
//  --------------  - 

  
function create_get_var($ar) 
    { 
      foreach (
$ar as $k => $v) 
        { 
          echo 
'$' $v[0] . ' = mysql_real_escape_string($_GET[' "'$v[0]'" ']);<br>'; 
        } 
    } 

  
//  ##############  # FUNCTION END  #  ############## 

  
if (isset($_GET['db'])) 
    { 
      if (
$_GET['db'] == 'Select database') 
          die; 
      
$_SESSION['database'] = $_GET['db']; 
      
$dbname mysql_real_escape_string($_GET['db']); 
      
$table_list get_tables($con$dbname); ?> 

<p></p>
<select value="lopper" name="table_list"
onchange="htmlData(m_insert.php, table=+this.value)" />
<?php 
      
foreach ($table_list as $k => $v) 
        { 
          echo 
'<option>' $v '</option>'; 
        } 
      echo 
'</select></p>'; 

      die; 
    } 

  if (isset(
$_GET['table'])) 
    { 
      
$db_selected mysql_select_db($_SESSION['database'], $con); 

      
$table mysql_real_escape_string($_GET['table']); 

      
$table_array desc_table($table$con); 

      
$sql_str sql_insert($table_array$table); 

      
$sql_update sql_update($table_array$table); 

      echo 
'<p>Table: ' $table '</p>'; 

      echo 
'<p>' $sql_str '</p>'; 

      echo 
'<p>' $sql_update '</p><br>'; 

      echo 
'<p>$_POST to variable</p>'; 
      
create_post_var($table_array); 

      echo 
'<p>$_GET to variable</p>'; 
      
create_get_var($table_array); 
    } 
  else 
    { 
      
$dbs get_db($con); 

      if (
$show_information_schema) 
        { 
          
//  remove information_schema from database list 
          
$res array_search('information_schema'$dbs); 
          unset(
$dbs[$res]); 
        } 
?> 

<select name="db_list"
onchange="htmlData(m_insert.php, db=+this.value)" />
    
 <?php 
      
foreach ($dbs as $k => $v) 
        { 
          echo 
'<option>' $v '</option>'; 
        } 
      echo 
'</select>'; 

      echo 
'<div id="txtResult"> </div>'; 
      die; 
    } 
?>

Friday, 3 October 2014

ob_clean in PHP

ob_clean — Clean (erase) the output buffer
Syntax: 

void ob_clean ( void )
This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

Return Values:

No value is returned.

ob_end_clean in PHP

ob_end_clean — Clean (erase) the output buffer and turn off output buffering
Syntax: 

bool ob_end_clean ( void )
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work.

Return Values:

Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Errors/Exceptions:

If the function fails it generates an E_NOTICE.

Examples:

The following example shows an easy way to get rid of all output buffers:

Example #1 ob_end_clean() example

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

ob_start in PHP

ob_start — Turn on output buffering
Syntax: bool ob_start ([ callable $output_callback = NULL [, int $chunk_size = 0 [, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS ]]] )
This function will turn output buffering on. 
While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). 
To output what is stored in the internal buffer, use ob_end_flush(). 
Alternatively, ob_end_clean() will silently discard the buffer contents.

Warning:
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active.
Just make sure that you call ob_end_flush() the appropriate number of times. 
If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

Parameters: 
output_callback: 
An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. 
The function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request. 
When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. 
If the output_callback is not a callable function, this function will return FALSE. 
This is the callback signature:

string handler ( string $buffer [, int $phase ] )
buffer :Contents of the output buffer.
phase: Bitmask of PHP_OUTPUT_HANDLER_* constants.
  If output_callback returns FALSE original input is sent to the browser.
       The output_callback parameter may be bypassed by passing a NULL value.
ob_end_clean(), 
ob_end_flush(), 
ob_clean(), 
ob_flush() and 
ob_start() may not be called from a callback function. 
If you call them from callback function, the behavior is undefined. 
If you would like to delete the contents of a buffer, return "" (a null string) from callback function. 
You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.

Note:
In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. 
ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.
chunk_size
If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size.
The default value 0 means that the output function will only be called when the output buffer is closed.
Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes.

flags
The flags parameter is a bitmask that controls the operations that can be performed on the output buffer.
The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly via PHP_OUTPUT_HANDLER_CLEANABLE | 
PHP_OUTPUT_HANDLER_FLUSHABLE | 
PHP_OUTPUT_HANDLER_REMOVABLE, or 
PHP_OUTPUT_HANDLER_STDFLAGS as shorthand.
Each flag controls access to a set of functions, as described below:
Constant Functions
PHP_OUTPUT_HANDLER_CLEANABLE ob_clean(), ob_end_clean(), and ob_get_clean().
PHP_OUTPUT_HANDLER_FLUSHABLE ob_end_flush(), ob_flush(), and ob_get_flush().
PHP_OUTPUT_HANDLER_REMOVABLE ob_end_clean(), ob_end_flush(), and ob_get_flush().
Return Values:Returns TRUE on success or FALSE on failure.
Changelog:

Version Description
5.4.0 The third parameter of ob_start() changed from a boolean parameter called erase 
(which, if set to FALSE,would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. 
Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. 
See the flags example for an example of how to handle this with code that needs to be compatible with both.
5.4.0 A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer.
4.3.2 This function was changed to return FALSE in case the passed output_callback can not be executed.

Example #1 
<?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>
Output:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>
Example #2 Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4

<?php

if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
    PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
  ob_start(null, 0, false);
}

?>