How to sum array values using php?

If you get all value from php array then you can use foreach. This is simple code which sum all value then give final result and also get average value .

<?php
// as of PHP 5.4
$ratings = [
    0 => ['rating' => 5],
    1 => ['rating' => 10],
    2 => ['rating' => 15],
    3 => ['rating' => 20],
    4 => ['rating' => 25],
];

$array_length = count($ratings); // array length
$final_result = 0;
$sum = 0; // this is store all sum value so first assign 0
foreach ($ratings as $ratingss) {
    $sum += $ratingss['rating']; // sum value with previous value and store it and no need to convert string type to int cause php do it
}
echo "Total Sum:".$sum ."<br>"; // this is final value
echo "Average:".$final_result = $sum / $array_length; // this is your desire result

?>

this is simple procedure got get all sum from php array.If you face any problem then please inform me.

Comment

Get information from the web server automatically

Server-sent events is a technology for where a browser gets automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5[1] by the W3C.

Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream. First create a simple html page which call php file and get result from this file

<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>

<script>
    if(typeof(EventSource)!=="undefined")
    {
        var source=new EventSource("http://localhost/result.php");
        source.onmessage=function(event)
        {
            document.getElementById("result").innerHTML+=event.data + "<br>";
        };
    }
    else
    {
        document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
    }
</script>

</body>
</html>

then create result.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Then you can see the result, without page refresh time will update

This is simple demo result

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

Comment

How to update session variable from dropdown change?

If you want to update your value like when drop down change then this value will set in php session in this case you can use ajax which help you lot. This is simple code which update session value when change drop down change .

This is total html and php code which need to update and browse data

<?php
session_start(); // for show your session value 
print_r($_SESSION); // remove this after check
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="myForm" action="/thanks" method="POST">

    <table>
        <tr>
            <td style="width:272px;">
                <select name="select_amount" id="select_amount" onchange="update_session_value(this.value)">
                    <option value="0">select a listing type</option>
                    <option value="10">Premium Listings</option>
                    <option value="20">Premium Blogs</option>
                    <option value="30">1 week sticky</option>
                </select></td>

            <td style="text-align:left;color:gray;">
                <span style="color:crimson;">*
            </span>Select a listing type
            </td>
        </tr>
    </table>
    <input type="submit" name="submit" class="button_add" onsubmit="return validateForm()">

</form>

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {

            }
        });
    }

</script>

Then create php file which update session value

<?php
session_start();
if( isset($_POST['select_amount']) ) {
    // save values from other page to session
    $_SESSION['amount'] = $_POST['select_amount'];

}
?>

For test you can refresh the page and check output or ajax function update this code

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {
 window.location.reload;
            }
        });
    }

</script>

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

Comment

How to add and remove attribute with jquery?

If you want to add and remove attribute using jquery then you can check this code. It will remove id and then when click remove then this id will remove. I also add css for understanding it.

This is html and css code


<div id="page_navigation1" style="border: 2px solid #ccc;height: 70px;width: 300px">Main Content</div>
<button id="add">Add</button>
<button id="remove">Remove</button>

This is css code

<style>
    #page_navigation1 {
        color: red;
    }
</style>

This is jQuery code which add and remove attribute

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#page_navigation1").addClass("page_navigation");

        $("#add").click(function(){
            $(".page_navigation").attr("id","page_navigation1");
        });
        $("#remove").click(function(){
            $(".page_navigation").removeAttr("id");
        });
    });
</script>

When run this code you will see this effect, If you find any problem then please inform me.

Comment

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

get ip from domain name using php

If you need to know ip address from domain name then you can use php which is very simple. You can use gethostbyname. gethostbyname — Get the IPv4 address corresponding to a given Internet host name . This is simple code


<?php
$ip = gethostbyname('https://techparkbd.com/');

echo $ip;
?>

Then Output is :

184.107.37.81 

If you find any problem then please 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