Month: January 2018

How to read child elements of XML using php?

If you want to get child elements from xml using php then you can use this code which help you to get child elements and some other options. This is simple demo code which help you. In this code first get child elements data then also child of child data. Just parse data using php simplexml_load_string function.

<?php
$string = <<<XML
<ORDERSTATUS>
    <DATE>23/01/18</DATE>
    <INVOICE>Test Data</INVOICE>
    <INVTOTAL Tax="25.00" Freight="28" SubTotal="80.00">100.0</INVTOTAL>
</ORDERSTATUS>
XML;

$xml = simplexml_load_string($string);

echo "DATE:".$xml->DATE."<br>";
echo "INVOICE:".$xml->INVOICE ."<br>";
echo "INVTOTAL:".$xml->INVTOTAL ."<br>";
echo  "Tax:".$xml->INVTOTAL->attributes()->Tax."<br>";
echo  "Freight:".$xml->INVTOTAL->attributes()->Freight."<br>";
echo  "SubTotal:".$xml->INVTOTAL->attributes()->SubTotal."<br>";

this code give you first child elements then also child of child elements . This is output this code

DATE:23/01/18
INVOICE:Test Data
INVTOTAL:100.0
Tax:25.00
Freight:28
SubTotal:80.00

If you face any problem then please inform me. I will try to help you.

Comment

How to rotate image and save new image using PHP ?

If you want to rotate image then save rotate image then you can use this simple php code.

<?php
$image = 'test.jpg';
 
// The file you are rotating
 
//How many degrees you wish to rotate
$degrees = 180;
 
// This sets the image type to .jpg but can be changed to png or gif
header('Content-type: image/jpeg') ;
 
// Create the canvas
$src = $image;
$system = explode(".", $src);
 
if (preg_match("/jpg|jpeg/", $system[1]))
{
$src_img=imagecreatefromjpeg($src);
}
if (preg_match("/png/", $system[1]))
{
$src_img = imagecreatefrompng($src);
}
if (preg_match("/gif/", $system[1]))
{
$src_img = imagecreatefromgif($src);
}
 
// Rotates the image
$rotate = imagerotate($src_img, $degrees, 0) ;
 
// Outputs a jpg image, you could change this to gif or png if needed
if (preg_match("/png/", $system[1]))
{
imagepng($rotate,$image);
}
else if (preg_match("/gif/", $system[1]))
{
imagegif($rotate, $image);
}
else
{
imagejpeg($rotate, $image);
}
 
imagedestroy($rotate);
imagedestroy($src_img);
 
?>

If you face any problem then please inform me. I will try to help you.

Comment

how to convert multidimensional array to single array using php?

For convert multidimensional array to single array then this is php code which help you lot . just follow this code

<?php
$your_array = array(0 => array('payment_id' => 3160), 1 => array('action' => 'update'), 2 => array('date' => '2017-05-17 09:59:40'), 3 => array('payment_date' => '23.05.201'));
echo "<pre>";
print_r($your_array);
$convert_array = array_reduce($your_array, 'array_merge', array());
echo "<pre>";
print_r($convert_array);

if you run this code then you will see this output like this :

Input array :

Array
(
    [0] => Array
        (
            [payment_id] => 3160
        )
 
    [1] => Array
        (
            [action] => update
        )
 
    [2] => Array
        (
            [date] => 2017-05-17 09:59:40
        )
 
    [3] => Array
        (
            [payment_date] => 23.05.201
        )
 
)

then output is :

Array
(
    [payment_id] => 3160
    [action] => update
    [date] => 2017-05-17 09:59:40
    [payment_date] => 23.05.201
)

if you face any problem then inform me, i will try to help you.

Comment

How to check if all inputs are not empty with jQuery?

If you want to check that all input fields not empty or any field empty then give error and show error message. You can do this easily using jQuery . This is simple code you can test it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
    textarea{height:auto;}
    select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
    select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
    select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
    .uneditable-textarea{width:auto;height:auto;}
    #country{height: 30px;}
	.highlight
	{
		border: 1px solid red !important;
	}
</style>
<script>
function test()
{
 var isFormValid = true;

    $(".bs-example input").each(function(){
        if ($.trim($(this).val()).length == 0){
		    $(this).addClass("highlight");
            isFormValid = false;
			$(this).focus();
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) { 
		alert("Please fill in all the required fields (indicated by *)");
	}

    return isFormValid;
}	
</script>
</head>
<body>
<div class="bs-example">
    <form onsubmit="return test()">
        <div class="form-group">
            <label for="inputEmail">Email</label>
            <input type="text" class="form-control" id="inputEmail" placeholder="Email">
        </div>
        <div class="form-group">
            <label for="inputPassword">Password</label>
            <input type="password" class="form-control" id="inputPassword" placeholder="Password">
        </div>
        <button type="submit" class="btn btn-primary">Login</button>
    </form>
</div>
</body>
</html>   

If you face any problem then please inform me.

Comment

How to checked checkbox is checked or not using PHP?

If you want to check that which checkbox checked and which not checked using php . Then you can check this simple code which give you this option.

<?php
if(isset($_POST['submit']))
{
  if(isset($_POST['submit']))
    {
       // $x = cout($_POST['checkbox']);
        for($x = 0;$x <= 4;$x++)
        {
            if(strlen($_POST['checkbox'][$x])>1)
            {
                echo "Checkbox is cheked<br>";
            }
            else{
                echo "Checkbox not checked<br>";
            }
        }
    }
 
 
}
 
 
?>

This is html code

<html>
<head>
 
</head>
<body>
<form enctype="multipart/form-data" action="" method="POST">
    <div id="text">
        <input type="checkbox" name="checkbox[0]"  />Checkbox1<br>
        <input type="checkbox" name="checkbox[1]"  />Checkbox2<br>
        <input type="checkbox" name="checkbox[2]"  />Checkbox3<br>
        <input type="checkbox" name="checkbox[3]"  />Checkbox4<br>
        <input type="checkbox" name="checkbox[4]"  />Checkbox5<br>
 
    </div>
    <input type="submit" value="Submit" name="submit" id="submit" />
</form>
</body>
</html>

Hope it will help you. If you find any problem then please inform me. i will try to help you

Comment

How to get MySQL column names?

Sometime we need to MYSQL table column name for many requirement, In this case we get columns name using simple MYSQL query. This is query and in this query i select column_name,column_type and table_name for more details . I use order by column_type so i can see it easily. You can change which you want

SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' order by DATA_TYPE;

If you want to check only double type filed then you can do it easily

SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,DATA_TYPE 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' AND DATA_TYPE like '%bigint%'  order by DATA_TYPE;

if you want to check which field allow null type etc then you can use this

SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,IS_NULLABLE,DATA_TYPE 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' and DATA_TYPE like '%bigint%' and IS_NULLABLE ='NO' order by COLUMN_TYPE;

Change your field name as your table field, if you face any problem then please inform me.

Comment

Sending data using Ajax to PHP

When you need to send data to server side then you can use Ajax to send data. This is simple code which help you.


<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>PHP, jQuery search demo</title>
    <link rel="stylesheet" type="text/css" href="my.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("input").keyup(function () {
                $('#results').html('');
                var searchString = $("#search_box").val();
                var data = 'search_text=' + searchString;
                if (searchString) {
                    $.ajax({
                        type: "POST",
                        url: 'http://localhost/search.php',
                        data: data,
                        dataType: 'text',
                        async: false,
                        cache: false,
                        success: function (result) {
                            $('#results').html(result);
                            //window.location.reload();

                        }
                    });
                }
            });
        });
    </script>

</head>
<body>
<div id="container">
    <div style="margin:20px auto; text-align: center;">
        <form method="post" action="do_search.php">
            <input type="text" name="search" id="search_box" class='search_box'/>
            <input type="submit" value="Search" class="search_button"/><br/>
        </form>
    </div>
    <div>

        <div id="searchresults">Search results :</div>
        <ul id="results" class="update">
        </ul>

    </div>
</div>

</body>
</html>

then create a search.php file which process ajax request value. you can also select data from database using this ajax data, also set this data to session etc.

This is search.php file

<?php 

$searchquery = $_POST['search_text']; 
echo $searchquery;
?>

if you face any problem then please inform me.

Comment

How to textarea lines convert to array using php?

If you want to textarea lines convert to array using php then check this demo code which help you.

Important thing that your textarea must need new line. In this code i added
for new line for better understand

$text = "Name:Jay <br/>
Email:jayviru@demo.com <br/>
Contact:9876541230";
$array_data = explode('<br/>', $text);

$final_data = array();
foreach ($array_data as $data){
    $format_data = explode(':',$data);
    $final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);

Then output is :

Array
(
    [Name] => Jay
    [Email] => jayviru@demo.com
    [Contact] => 9876541230
)

And if your text area value get using php variable then simple use this code

<?php
$text = $_POST['filed_value'];
$array_data = explode(PHP_EOL, $text);

$final_data = array();
foreach ($array_data as $data){
    $format_data = explode(':',$data);
    $final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);

This is get same value, if you face any problem then please inform me. I will try to help you

Comment

backup total database using php code.

If you want to backup total database using php code then you can follow this code. In this code which backup total db , if you want to backup some table then you can also use this code. This is simple code.

<?php

// call function which backup database
backup_database('localhost', 'root', '', 'database_name', '*');

// this is main function which process all table data and ready for export
// first host name, db_username, db_password, db_name, when use * then all table
function backup_database($hostname, $user, $pass, $dbname, $tables = '*')
{
    $link = mysqli_connect($hostname, $user, $pass, $dbname);

    if (mysqli_connect_errno()) {
        echo "Failed to connect: " . mysqli_connect_error();
        exit;
    }

    // set utf8 character set
    mysqli_query($link, "SET NAMES 'utf8'");

    // get all table when * and insert all table into tales array
    if ($tables == '*') {
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
        while ($row = mysqli_fetch_row($result)) {
            $tables[] = $row[0];
        }
    } else {
        // when table name specified then process
        $tables = is_array($tables) ? $tables : explode(',', $tables);
    }

    $return = '';
    // process table and process filed using this loop
    foreach ($tables as $table) {
        $result = mysqli_query($link, 'SELECT * FROM ' . $table);

        // get all fields and process them
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);

        $return .= 'DROP TABLE IF EXISTS ' . $table . ';';
        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE ' . $table));
        $return .= "\n\n" . $row2[1] . ";\n\n";
        $counter = 1;

        // process all fields under this table
        for ($i = 0; $i < $num_fields; $i++) {
            while ($row = mysqli_fetch_row($result)) {
                // make table and format table
                if ($counter == 1) {
                    $return .= 'INSERT INTO ' . $table . ' VALUES(';
                } else {
                    $return .= '(';
                }
                // make all fields and format also
                for ($j = 0; $j < $num_fields; $j++) {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n", "\\n", $row[$j]);
                    if (isset($row[$j])) {
                        $return .= '"' . $row[$j] . '"';
                    } else {
                        $return .= '""';
                    }
                    if ($j < ($num_fields - 1)) {
                        $return .= ',';
                    }
                }
                // when all row done then return using end line
                if ($num_rows == $counter) {
                    $return .= ");\n";
                } else {
                    $return .= "),\n";
                }
                ++$counter;
            }
        }
        // return using new line
        $return .= "\n\n\n";
    }
    // ready database for export and make sql file
    $fileName = 'backup-' . $dbname . '.sql';
    $handle = fopen($fileName, 'w+');
    fwrite($handle, $return);
    if (fclose($handle)) {
        echo "Backup Done: " . $fileName;
        exit;
    }
}

?>

if you face any problem then please inform me. I will try to help you

Comment

How do I determine browser name using JavaScript?

If you want to know which browser access your page or other case then you can do this using javascript. This is simple code which you can use.

<script>
    function get_browser() {
        var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(M[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE';
        }
        if (M[1] === 'Chrome') {
            tem = ua.match(/\bOPR\/(\d+)/)
            if (tem != null) {
                return 'Opera'
            }
        }
        M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) {
            M.splice(1, 1, tem[1]);
        }
        return M[0];
    }

    var browser = get_browser();

    alert(browser)

</script>

this code give alert browser name. If you face any problem then please inform me.

Comment