1 . How to reorder buttons on page refresh in a form?

Answer :

This should work if you do not have an error in the database

<?
    session_start();
    include_once 'dbconnect.php';

    $res=mysqli_query($con, "SELECT * FROM users WHERE user_id=".$_SESSION['user']);
    $userRow=mysqli_fetch_assoc($res);

    $array = array(
       $userRow['test1'] => array( 'class' => 'foo', 'name' => 'update' ),
        $userRow['test2']=> array( 'class' => 'john', 'name' => 'update' ),
        $userRow['test3'] => array( 'class' => 'x', 'name' => 'update' ),
        $userRow['test4'] => array( 'class' => 'a', 'name' => 'update' ),
        $userRow['test5'] => array( 'class' => 'b', 'name' => 'update' ),
        $userRow['test6'] => array( 'class' => 'c', 'name' => 'update' ),
        $userRow['test7'] => array( 'class' => 'd', 'name' => 'update' ),
        $userRow['test8'] => array( 'class' => 'e', 'name' => 'update' ),
        $userRow['test9'] => array( 'class' => 'f', 'name' => 'update' ),
        $userRow['test10'] => array( 'class' => 'g', 'name' => 'update' ),
        $userRow['test11'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test12'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test13'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test14'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test15'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test16'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test17'] => array( 'class' => 'h', 'name' => 'idchange' ),
        $userRow['test18'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test19'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test20'] => array( 'class' => 'h', 'name' => 'update' ),
    );

    uksort( $array, function() { return rand() > rand(); } );

    foreach( $array as $item => $atts ){
        echo '<form action="check1.php" method="post">';
        echo '<div class="'. $atts['class'] .'"><button name="'. $atts['name'] .'" type="submit" >'. $item .'</button></div>';
        echo '</form>';
    }

Leave a Comment

Name  
  Email   
Message
1 . Codeigniter, join table properties overrides other properties?
 

Answer :

$this->db->select("*, questions.id as question_id");

It's obvious that properties with the same name will be overriden. That's why you should assign to them 'unique' names in select statement.


2 . May I choose php platform? Really is this feature true?

Answer :

 PHP has always been a wise choice because it runs on most Operating Systems. 
It has a massive library. 
It has massive contributions. 
It has been around for a long time. 
There is tons of add-ons, source code and support via user groups etc. 
The product is well maintained and well documented. 
It is easy to install and configure. 
It is free and Open Source. 
It interfaces well .. 

I can go on and on and on...... 

Java is equally, if not more, important to know. 
It can call PHP for Ajax type applications.


3 . From Javascript Date.now to PHP date?
 

Answer :

Date.now() in Javascript returns a timestamp in milliseconds, whereas Carbon's createFromTimestampmethod expects seconds.

There's a separate function you can use that accepts a millisecond-precision value. Try:

 $now = \Carbon\Carbon::createFromTimestampMs($request->input('time'));

4 . Multi Level user groups PHP Mysql while infinite loop?
 

Answer :

I don't understand what you tried to do in your last code, but it should work if you change echo $data['category'] = getCategories(0, $category); in your first code block to:

$data['category'] = "";
foreach (array_keys($category['parent_cats']) as $parent)
{
    $data['category'] .= getCategories($parent, $category);
}
echo $data['category'];

It does the same thing as you already did but multiple times with a different $parent every time for each cat.


5 . How to insert and update the mysql table in php??????????

Answer :

<?php 

$DBHost = "localhost"; 
$DBUser = "root"; 
$DBPass = ""; 
$DBName = "databaseName"; 

$con = mysql_connect($DBHost, $DBUser, $DBPass); 
$db = mysql_select_db($DBName, $con); 
mysql_query(' 
CREATE TABLE IF NOT EXISTS `table_sample` ( 
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , 
`name` VARCHAR( 75 ) NOT NULL, 
`email` VARCHAR( 128 ) NOT NULL 
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;'); 

$sql = "INSERT INTO `table_sample` (`id`, `name`, `email`) 
VALUES (NULL,'YouName','emailidof the user'); 
$result = mysql_query($sql); 

$sql = "UPDATE `table_sample` SET `name` = 'Youname', `email` = 'emailidof the user' WHERE `id` = '2'; 
$result = mysql_query($sql); 
?>



6 . Remove Woocommerce sidebar from any theme?
 

Answer :

The best and simple way that works with all themes is to use the get_sidebar Wordpress action hook this way:

add_action( 'get_sidebar', 'remove_woocommerce_sidebar', 1, 1 );
function remove_woocommerce_sidebar( $name ){
    if ( is_woocommerce() && empty( $name ) )
        exit();
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

You might need to make some CSS changes on some html related containers

This code works on any theme as all themes use get_sidebar() Wordpress function for sidebars (even for Woocommerce sidebar) and get_sidebar action hook is located inside this function code.


7 . What is the difference between $GET, $POST, $REQUEST and $COOKIE in PHP?

Answer :

Those are predefined variables in php. 
when you send something from html code you need to chose method. Methods are get and post. 
example: 
<form action="example.php" method=(get or post)> 
<input type=text name='textfield'/> 
</form> 

when you set the get method you can receive value in a example.php file using $_GET or $_REQUEST 
example: 
NAME=$_REQUEST["textfield"]; 
or 
NAME=$_GET["textfield"]; 

get method sends all information via url 
examle www.yahoo.com?ID=25 where id is variable with value 25. 
This is an example where you should use get. 
You have 2 limitations. 
1. The max value of characters you can send via url is 1024 including url 
2. If you enter password field with hidden characters it will be visible in url like 
www.yahoo.com?Username='Bojan';Passwor... so, do not use get for this. 

The post method is much more flexible for sending vulnerable kind of data because they travel in a hidden form. 
when you set the post method you can receive value in a example.php file using $_POST or $_REQUEST 
example: 
NAME=$_REQUEST["textfield"]; 
or 
NAME=$_POST["textfield"]; 

So, you can conclude that $_REQUEST is an universal variable to "catch" all sent data from html form. 

And $_COOKIE variable is an associative array of variables passed to the current script via HTTP Cookies.


8 . Custom cart item price calculation based on custom fields in Woocommerce?
 

Answer :
$total_price = ($height/3 * $width/30 + 3)*1.48;

As everything works, you will be able to make easily changes in your calculation if needed…

The code:

// Display custom input fields in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'add_product_custom_fields', 20 );
function add_product_custom_fields(){
    $domain =  'woocommerce';
    $value = isset( $_POST['height_option'] ) ? sanitize_key( $_POST['height_option'] ) : '';
    printf( '<label>%s</label><input name="height_option" value="%s" type="number"/><br>', __( 'Height', $domain ), esc_attr( $value ) );

    $value = isset( $_POST['width_option'] ) ? sanitize_key( $_POST['width_option'] ) : '';
    printf( '<label>%s</label><input name="width_option" value="%s" type="number"/><br>', __( 'Width', $domain ), esc_attr( $value ) );
}

// Add custom fields data to cart items and make calculation price
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 20, 2 );
function custom_add_cart_item_data( $cart_item, $product_id ){

    if( isset( $_POST['height_option'] ) )
        $cart_item['custom_data']['height'] = sanitize_key( $_POST['height_option'] );

    if( isset( $_POST['width_option'] ) )
        $cart_item['custom_data']['width'] = sanitize_key( $_POST['width_option'] );

    // Make calculation and save calculated  price
    if( isset( $_POST['height_option'] ) && isset( $_POST['width_option'] ) ){
        $height      = (int) sanitize_key( $_POST['height_option'] );
        $width       = (int) sanitize_key( $_POST['width_option'] );

        if( $width > 0 && $height > 0 ){
            $total_price = ( ( $height / 3 ) * ( $width / 30 ) + 3 ) * 1.48; // <== The calculation
            $cart_item['custom_data']['price'] = round($total_price, 2); // Save the price in the custom data
        }
    }

    return $cart_item;
}

// Display custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
function display_custom_cart_item_data( $cart_data, $cart_item ) {
    $domain = 'woocommerce';

    if ( isset( $cart_item['custom_data']['height'] ) ){
        $cart_data[] = array(
            'name' => __( 'Height', $domain ),
            'value' => $cart_item['custom_data']['height']
        );
    }
    if ( isset( $cart_item['custom_data']['width'] ) ){
        $cart_data[] = array(
            'name' => __( 'Width', $domain ),
            'value' => $cart_item['custom_data']['width']
        );
    }
    return $cart_data;
}

// Set the new calculated price replacing cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_calculated_price', 20, 1 );
function set_cart_item_calculated_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ){
        if( ! isset( $cart_item['custom_data']['price'] ) ){
            continue;
        }
        if( $cart_item['custom_data']['price'] > 0 ){
            // Set the calculated item price (if there is one)
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['price'] );
        }
    }
}


// Get cart item custom data and update order item meta and display in orders and emails
add_action( 'woocommerce_checkout_create_order_line_item', 'save_order_item_custom_meta_data', 10, 2 );
function custom_add_order_item_meta( $item_id, $values ) {
    $domain = 'woocommerce';

    if( isset( $cart_item['custom_data']['height'] ) )
        $item->update_meta_data( __( 'Height', $domain ), $values['custom_data']['height'] );

    if( isset( $cart_item['custom_data']['width'] ) )
        $item->update_meta_data( __( 'Width', $domain ), $values['custom_data']['width'] );
}

Code goes in function.php file of your active child theme (or active theme).


9 . Php database creating acces denied,plz help me out.?

Answer :

<?php 
include 'config.php'; 
include 'opendb.php'; 

mysql_create_db('phpcake'); 

include 'closedb.php'; 
?> 

If you want to create tables in the database you just created don't forget to call mysql_select_db() to access the new database. 


<?php 
include 'config.php'; 
include 'opendb.php'; 

$query = 'CREATE DATABASE phpcake'; 
$result = mysql_query($query); 

mysql_select_db('phpcake') or die('Cannot select database'); 

$query = 'CREATE TABLE contact( '. 
'cid INT NOT NULL AUTO_INCREMENT, '. 
'cname VARCHAR(20) NOT NULL, '. 
'cemail VARCHAR(50) NOT NULL, '. 
'csubject VARCHAR(30) NOT NULL, '. 
'cmessage TEXT NOT NULL, '. 
'PRIMARY KEY(cid))'; 

$result = mysql_query($query); 

include 'closedb.php'; 
?>


10 . Multiple ajax requests from one page + how to do + best practice?
 

Answer :

google charts only needs to be loaded once per page load,
not every time you need to draw a chart

also, google.charts.load can be used in place of --> $(document).ready
it will wait for the page to load before executing the callback / promise

recommend setup similar to following snippet...

google.charts.load('current', {
  packages: ['corechart', 'bar']
}).then(function () {
  $.ajax({
    url: 'data.php',
    dataType: 'json'
  }).done(drawChart1);

  $.ajax({
    url: 'data.php',
    dataType: 'json'
  }).done(drawChart2);
});

function drawChart1(result) {
  ...
}

function drawChart2(result) {
  ...
}


11 . Why does Laravel Migrations on Windows migrates the first table but not the others?
 

Answer :

What is your version of mysql? as per documentation: If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

12 . PHP Programming is really good Language for Web Developing?

Answer :

PHP is a great language to know and is getting even better. 

Consider that there are now over 65 million WordPress installations on the web and there is no sign of it stopping anytime soon. WorPress is written in PHP and so are the themes that are making great money on the web. Also, PHP has come to the mobile platform creating yet another whole market for programming. Mobile used to be dominated by Java programmers but now that is changing. 

So the answer is yes, there is a long career opportunity in PHP programming and it pays well.


13 . Query function not work in php7?
 

Answer :

when I updated my PHP-scripts to PHP7 I had issues with

mysqli_fetch_array()

you should replace it with a function like

mysqli_fetch_assoc()

14 . Wired behaviour of .htaccess while i'm forcing to redirect https and skip /index.php in CodeIgniter 2.2.6?

Answer :

Try changing with the below, instead of

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

to

RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I have faced this like problems with the server cache for the 500 errors while editing the .htaccess, try with the incognito mode


15 . PHP vs ASP.NET for Social Networking Site.....?

Answer :

We do NOT write in ASP, but in PhP. Here is why. 
PHP, [www.php.net], while loosely based on C and Perl, has never faced the overwhelming complications ASP has. PHP is an object oriented language - though scripts need not necessarily be developed that way (there are still a vast number of developers preferring procedural programming, and PHP caters to both schools). PHP is both cross platform and open source, available for every major operating system and works with most web servers. It is easily extendable by anyone capable of coding in C, and comes pre-bundled with more functionality than ASP could ever offer. Simple capabilities, such as FTP, data compression, file uploads, XML, MD5, encryption and email are not included in ASP and require expensive, third-party packages to be installed. All of this functionality and more are built right into PHP. Complex functions such as dynamic images, IMAP, SNMP, dynamic flash, PDF, native access (non ODBC) to Oracle, Ovrimos, Postgre, Sybase, mySql, MSSQL, Ingres, Interbase and Informix databases, LDAP, and sockets, just to name a few, are available for free to any installation of PHP, but are not (and probably never will be) available with ASP. In addition, one could make the point that PHP is a more mature language than ASP. ASP has only been around since 1996; PHP has been around since 1994, and has a huge base of developers working on it every waking minute of every day; bugs are usually fixed within minutes of being reported and new features are being integrated daily. 

1) ASP is significantly slower than PHP, for obvious reasons. Primarily, PHP runs on notoriously fast Unix and Linux servers which have for years outpaced Windows running on comparable hardware. ASP does not run on any operating system other than Windows, and even then, only in IIS and PWS. I could discuss countless reasons why IIS makes a terrible web server, but that would be a discussion all on it's own. PHP runs on almost any web server, on 
almost any platform. I have even built a web server in PHP which was capable of executing PHP scripts. 
2) ASP natively supports only Access and MSSQL, whereas PHP natively supports a huge number of databases. They both support ODBC equally well. MySQL is a database that PHP closely integrates with; it is a very powerful database that rivals Oracle in speed. Like PHP, MySQL is free, and blows most other databases out of the water. Another hidden cost with ASP is the database angle; Microsoft expects you to develop using Access and when your webpage outgrows it, to switch to MSSQL, an extremely expensive option. 

3) While even the best software has glitches, PHP has notoriously few. The PHP development team has an outstanding reputation for fixing bugs, and in order to streamline the process they even have an online system through which new bug reports can be submitted. Most bugs are resolved within 24 hours, and I'm speaking from experience here. There are a huge number of outstanding bugs in ASP which will probably never be fixed. Unless you're a major corporation, chances are that your bug report to Microsoft will likely go unanswered. 

4) And finally, cost. PHP is free. ASP isn't free. If you want to use ASP, you have to use IIS, and if you want to use IIS, you have to buy Windows. Traditionally, the cost of Windows has been high. Microsoft has been aggressively trying to reduce this factor but they're hardly going to give Windows away for free. The cost of running an ASP-based website implies a full Windows server platform; development costs are higher, software licenses are expensive and speed, security and flexibility are all sacrificed. 
There's a reason that Unix and Linux are dominant in the server market; money, security and performance all speak volumes.