Skip to main content

Get Google Calendar Event List in WordPress

<a href="https://console.cloud.google.com/apis/credentials">Get Your Api Credentials Here</a> <a href="https://calendar.google.com/calendar">Get your Calender ID</a> <?php include_once("wp-load.php"); function  get_calender_events() { $params = array(); /*Get current date*/ $current_date  = date('Y-m-d H:i:s'); /*Convert it to google calendar's rfc_format */ $rfc_format = date("c", strtotime($current_date)); $params[] = 'orderBy=startTime'; $params[] ='maxResults=100'; $params[] = 'timeMin='.urlencode($rfc_format); $url_param = ''; foreach($params as $param) { $url_param.= '&'.$param; } $calender_id = "calender_id"; $client_key =  "client_key"; $url = "https://www.googleapis.com/calendar/v3/calendars/".$calender_id."/events?key=".$client_key."&singleEvents=true".$url_param; $list_events = wp_remote_post($url, ...

PHP interview questions and answers for freshers

PHP interview questions and answers for freshers

1.What is the difference between a static and Dynamic Web site?
2.What is the meaning of Open Source Software?
3.Why was PHP developed, what it is used for, and where can you get it?
4.What are the benefits of using PHP and MySQL?

The above FOUR questions you should know before go to this topic.
Ans:
1 A static website is one that is written in HTML only. Each page is a separate document and there is no database that it draws on. What this means functionally is that the only way to edit the site is to go into each page and edit the HTML - So you would have to do it yourself using a web page editor such as FrontPage or Dreamweaver, or pay your web developer to make updates for you.

A dynamic website is created by webdevelopers who are strong in ASP.Net, PHP, JAVA and more... This website pages contains data is retrieved from certain database. Each time the viewer entering a page, the contents of that page is retrieved from the database. The administrator can change the content and images from admin panel. This is one that changes or customizes itself frequently and automatically.

2. Open-Source Software (OSS) is computer software that is available in source code form: the source code and certain other rights normally reserved for copyright holders are provided under a software license that permits users to study, change, improve and at times also to distribute the software.Open Source Software means it is a free software and no need to buy, we can use full functionallities from this software with certain Terms & Conditions. This license allows modifications and derived works, and allows us to be distributed under the same terms as the license of the original software.

3. PHP developed for less script, time saving, Free Open Source Software and runs on different platforms such as Windows, Linux, Unix, etc. PHP compatible with almost all servers used today such as Apache, IIS, etc.

The PHP scripting language resembles JavaScript, Java, and Perl, These languages all share a common ancestor, the C programming language. PHP has full access to the information that the server has, and very little access to information that the client has. In fact, it only has information that the client tells the server and that the server passes on to PHP. Because it is on the server, however, PHP cannot be modified by the client. While you cannot necessarily trust the information that the client gives to PHP, you can trust that your PHP is doing what you told it to do. Because PHP is on the server end, your PHP scripts can affect your server -- such as by keeping an activity log or updating a database.

PHP is free dowload from the offical PHP resource



4. One of the main reasons that businesses choose PHP is its simplicity and ease of use. PHP competes against a number of other web scripting solutions such as Active Server Pages and PERL, but none of these languages are as easy to learn as PHP. Further, some languages require a moderate amount of programming background before a developer can get up to speed in development. With PHP, however, even non-programmers have been able to develop web-based solutions within a matter of days after going through the basic tutorials on PHP. PHP commands are simply embedded into the same web page with HTML commands, and execute on the server to deliver the web pages to the user.

Another big advantage of PHP is its interoperability with multiple operating systems. A company can use PHP with either Linux, Windows or Macs for example. They can also use PHP with the popular open source Apache server. Compare that with Microsoft’s Active Server Pages, by contrast, which is primarily designed for Microsoft-enabled servers. Portability is becoming a chief concern for businesses that use one or more operating systems in their businesses. Businesses save money by using PHP to leverage their existing I.S. resources rather than investing large sums of money to purchase proprietary products.
  1. What is PHP? PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning
  2. What is the use of "echo" in php? It is used to print a data in the webpage, Example: <?php echo 'Car insurance'; ?> , The following code print the text in the webpage
  3. How to include a file to a php page? We can include a file using "include() " or "require()" function with file path as its parameter.
  4. What's the difference between include and require? If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
  5. require_once(), require(), include().What is difference between them? require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
  6. Differences between GET and POST methods ? We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .
  7. How to declare an array in php? Eg : var $arr = array('apple', 'grape', 'lemon');
  8. What is the use of 'print' in php? This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list.
    Example print('PHP Interview questions');
    print 'Job Interview ');
  9. What is use of in_array() function in php ? in_array used to checks if a value exists in an array
  10. What is use of count() function in php ? count() is used to count all elements in an array, or something in an object
  11. What’s the difference between include and require? It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
  12. What is the difference between Session and Cookie? The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
  13. How to set cookies in PHP? Setcookie("sample", "ram", time()+3600);
  14. How to Retrieve a Cookie Value? eg : echo $_COOKIE["user"];
  15. How to create a session? How to set a value in session ? How to Remove data from a session? Create session : session_start();
    Set value into session : $_SESSION['USER_ID']=1;
    Remove data from a session : unset($_SESSION['USER_ID'];
  16. what types of loops exist in php? for,while,do while and foreach (NB: You should learn its usage)
  17. How to create a mysql connection? mysql_connect(servername,username,password);
  18. How to select a database? mysql_select_db($db_name);
  19. How to execute an sql query? How to fetch its result ? $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; ");
    $result = mysql_fetch_array($my_qry);
    echo $result['First_name'];
  20. Write a program using while loop $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; ");
    while($result = mysql_fetch_array($my_qry))
    {
    echo $result['First_name'.]."<br/>";
    }
  21. How we can retrieve the data in the result set of MySQL using PHP?
    • 1. mysql_fetch_row
    • 2. mysql_fetch_array
    • 3. mysql_fetch_object
    • 4. mysql_fetch_assoc
  22. What is the use of explode() function ? Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
    This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.
  23. What is the difference between explode() and split() functions? Split function splits string into array by regular expression. Explode splits a string into array by string.
  24. What is the use of mysql_real_escape_string() function? It is used to escapes special characters in a string for use in an SQL statement
  25. Write down the code for save an uploaded file in php. if ($_FILES["file"]["error"] == 0)
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  26. How to create a text file in php? $filename = "/home/user/guest/newfile.txt";
    $file = fopen( $filename, "w" );
    if( $file == false )
    {
    echo ( "Error in opening new file" ); exit();
    }
    fwrite( $file, "This is a simple test\n" );
    fclose( $file );
  27. How to strip whitespace (or other characters) from the beginning and end of a string ? The trim() function removes whitespaces or other predefined characters from both sides of a string.
  28. What is the use of header() function in php ? The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.
  29. How to redirect a page in php? The following code can be used for it, header("Location:index.php");
  30. How stop the execution of a php scrip ? exit() function is used to stop the execution of a page
  31. How to set a page as a home page in a php based site ? index.php is the default name of the home page in php based sites
  32. How to find the length of a string? strlen() function used to find the length of a string
  33. what is the use of rand() in php? It is used to generate random numbers.If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.
  34. what is the use of isset() in php? This function is used to determine if a variable is set and is not NULL
  35. What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ? mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array() fetches an associative array, a numeric array, or both
  36. What is mean by an associative array? Associative arrays are arrays that use string keys is called associative arrays.
  37. What is the importance of "method" attribute in a html form? "method" attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the URL.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
  38. What is the importance of "action" attribute in a html form? The action attribute determines where to send the form-data in the form submission.
  39. What is the use of "enctype" attribute in a html form? The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as "multipart/form-data" when we are using a form for uploading files
  40. How to create an array of a group of items inside an HTML form ? We can create input fields with same name for "name" attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP.
    For instance :
    <input name="MyArray[]" />  <input name="MyArray[]" />  <input name="MyArray[]" />  <input name="MyArray[]" />
  41. Define Object-Oriented Methodology Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships
  42. How do you define a constant? Using define() directive, like define ("MYCONSTANT",150)
  43. How send email using php? To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg : mail($to,$subject,$message,$headers);
  44. How to find current date and time? The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don't, the current timestamp will be used.
  45. Difference between mysql_connect and mysql_pconnect? There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.
  46. What is the use of "ksort" in php? It is used for sort an array by key in reverse order.
  47. What is the difference between $var and $$var? They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var. For example, if $var contains "message", $$var is the same as $message.
  48. What are the encryption techniques in PHP MD5 PHP implements the MD5 hash algorithm using the md5 function,
    eg : $encrypted_text = md5 ($msg);
    mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] );
    Encrypts plaintext with given parameters
  49. What is the use of the function htmlentities? htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
  50. How to delete a file from the system Unlink() deletes the given file from the file system.
  51. How to get the value of current session id? session_id() function returns the session id for the current session.
  52. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
    • Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.
    • mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
    • mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
  53. What are the different types of errors in PHP ? Here are three basic types of runtime errors in PHP:
    • 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior.
    • 2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
    • 3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.
  54. what is sql injection ? SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications
  55. What is x+ mode in fopen() used for? Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  56. How to find the position of the first occurrence of a substring in a string strpos() is used to find the position of the first occurrence of a substring in a string
  57. What is PEAR? PEAR is a framework and distribution system for reusable PHP components.The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style.PEAR is broken into three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The Core Components include the base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing functions. The PEAR Packages include functionality providing for authentication, networking, and file system features, as well as tools for working with XML and HTML templates.
  58. Distinguish between urlencode and urldecode? This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the urldecode->Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function.
  59. What are the different errors in PHP? In PHP, there are three types of runtime errors, they are:
    Warnings:
    These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
    Notices:
    These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
    Fatal errors:
    These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.
  60. How can we get the browser properties using php?
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
?>
61. How can we submit from without a submit button?
We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit(); function to submit the form.

Q. How we can get the data from the mysql query result set in PHP?
Ans. There are 4 ways to get the data from mysql query result set.
     1. mysql_fetch_row.
     2. mysql_fetch_array.
     3. mysql_fetch_object.
     4. mysql_fetch_assoc.
Q. Explain the difference between $message and $$message.
Ans. $message is used to store the variable and $$message is used to store variable of another variable. For example  $message = ‘Mohit’ and $$message = ‘is a programmer’. We know in php we use $ for a variable. But $$message is a different case. It creates a variable name $Mohit with the value “is a programmer”.
Q. What is include, include_once, require, require_once?
Ans. 1.The include statement includes a file in a php document. If given file in include statement does not exist, it generates a warning but script will continue, processing will not halt.
     2. The require statement includes a file in a php document like include statement but the difference is this if include file does not exist in the required place.It will the halt the processing and generate the fatel error.
     3. The include_once() statement includes  the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
     4. The require_once() should be used in cases where the same file might be included more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc. Processing will the halt if includde file does not exist like require statment.
Q. How many types of tables exists in mysql?
Ans. 5 types of tables presents in mysql database.
     1. MyISAM (default storage engine).
     2. Heap
     3. Merge
     4. INNO DB
     5. ISAM
  we will explain these storage engines in upcoming posts.
Q. What is the use of nl2br()?
Ans. The nl2br() function inserts HTML line breaks (<BR />) before all newlines in a string.
     For Example
     echo nl2br(“One line.\nAnother line.”);
     Output:
     One line.
     Another line.
     Html Source will look like this:
     One line.<br />
     Another line.
     
Q. Explain different type of errors in PHP.

Ans.There are three types of errors:
    1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script. For  example, accessing a variable that has not yet been defined.By default, such errors are not displayed to the user at all – although, as you will see, you can change this default behaviour.
    2. Warnings: These are more serious errors For example, attempting to include() a file which does not exist. By default, these errors are displayed to the user,but they do not  result in script termination.
    3. Fatal errors: These are critical errors For example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behaviour is to display them to the user when they take place.
Q. Explain the difference between the functions unlink and unset?
Ans. unlink() deletes the given file from the file system. unset() makes a variable undefined.
Q. What is the maximum size of a file that can be uploaded using PHP and how can we change this?
Ans. By default the maximum size is 2MB and we can change the following setup at php.ini upload_max_filesize = 5MB
Q. How can we increase the execution time of a PHP script?
Ans.  By changing the following setup at php.ini max_execution_time = 30 (in seconds).
Q.  How can we get the value of current session id?
Ans. session_id() returns the session id for the current session.
Q. How can we know the number of elements of an array?
Ans. There are two ways
     1) sizeof($array)
     2) This function is an alias of count(), count($array)
Q. How can we optimize select Mysql Query?
Ans:  1. First of all instead of using select * from tablename, use select column1, column2, column3.. from tablename.
          2. Look for the opportunity to introduce index in the table you are querying.
          3. Use limit keyword if you are looking for any specific number ofrows from the result set.
Q. How can we destroy the cookie?
Ans. Set the cookie in past.
Q. Explain different  type of functions in sorting an array?
Ans.  sort(), arsort(),asort(), ksort(),natsort(),natcasesort(),rsort(), usort(), array_multisort(), uksort() etc. We will explain in details these function in our upcoming posts.
Q. How can I know that a variable is a number or not using a JavaScript?
Ans. 1. is_numeric ( mixed var) returns TRUE if var is a number ,FALSE otherwise.
         2. isNaN(mixed var).The isNaN() function is used to check if a value is not a number.
Q. How can we send mail using JavaScript?
Ans. JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send.
Q. What is the purpose of the following files having extensions 1) .frm 2) .myd 3) .myi? What do these files contain?
Ans.  In MySql, the default table type is MyISAM. Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type.The ‘.frm’ file stores the table definition.The data file has a ‘.MYD’ (MYData) extension.The index file has a ‘.MYI’ (MYIndex) extension.
Q. How can we find the number of rows in a table using MySQL?
Ans: Use this for mysql
     >SELECT COUNT(*) FROM table_name;
Q. How can we find the number of rows in a result set using PHP?
Ans. $result = mysql_query($sql, $db_link);
        $num_rows = mysql_num_rows($result);
       echo “$num_rows rows found”;
Q. What type of inheritance that PHP supports?
Ans. In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.
Q. What is the difference between Primary Key and Unique key?
Ans. Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL.
     Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can     be only one primary key for a table but there can be more than one unique for a table.
Q. How can we know the number of days between two given dates using MySQL?
Ans. SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);
Q. How to get Query String in PHP for http request?
Ans. $_GET[] and $_REQUEST[]
Q. How to get the http Request in PHP?
Ans. When PHP is used on a Web server to handle a HTTP request, it converts information submitted in the HTTP request as predefined variables:
     1.$_GET – Associate array of variables submitted with GET method.
     2.$_POST – Associate array of variables submitted with POST method.
     3.$_COOKIE – Associate array of variables submitted as cookies.
     4.$_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.
     5. $_SERVER – Associate array of all information from the server and the HTTP request.    
Q. What’s MySQL?
Ans. MySQL is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database.
Q. What is DDL, DML and DCL?
Ans. If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system. 
Q. How do you get the number of rows affected by query?
Ans. SELECT COUNT (user_id) FROM users would only return the number of user_id’s.
Q. If the value in the column is repeatable, how do you find out the unique values?
Ans.Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;
Q. How do you return the a hundred books starting from 25th?
Ans.SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
Q. How would you write a query to select all teams that won either 2, 4, 6 or 8 games?
Ans. SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8) .
Q. How would you select all the users, whose phone number is null?
Ans. SELECT user_name FROM users WHERE ISNULL(user_phonenumber).
Q. What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ?
Ans. It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id.
Q. How do you find out which auto increment was assigned on the last insert?
Ans. SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
Q. On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do?
Ans. What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.
Q. When would you use ORDER BY in DELETE statement?
Ans. When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.
Q. How can you see all indexes defined for a table?
Ans. SHOW INDEX FROM techpreparation_questions.
Q. How would you change a column from VARCHAR(10) to VARCHAR(50)?
Ans. ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50). 
Q. How would you delete a column?
Ans. ALTER TABLE techpreparation_answers DROP answer_user_id.
Q. How would you change a table to InnoDB?
Ans. ALTER TABLE techpreparation_questions ENGINE innodb.
Q. How do you concatenate strings in MySQL?
Ans. CONCAT (string1, string2, string3) .
Q. How do you get a portion of a string?
Ans. SELECT SUBSTR(title, 1, 10) from techpreparation_questions.
Q. How do you get the month from a timestamp?
Ans. SELECT MONTH(techpreparation_timestamp) from techpreparation_questions.
Q. How do you offload the time/date handling to MySQL?
Ans. SELECT DATE_FORMAT(techpreparation_timestamp, ‘%Y-%m-%d’) from techpreparation_questions; A similar TIME_FORMAT function deals with time. 
Q. How do you add three minutes to a date?
Ans. ADDDATE(techpreparation_publication_date, INTERVAL 3 MINUTE) 
Q. How do you start and stop MySQL on Windows?
Ans. net start MySQL, net stop MySQL 
Q. How do you start MySQL on Linux?
Ans. /etc/init.d/mysql start 
Q. What’s the default port for MySQL Server?
Ans. 3306 
Q. What does tee command do in MySQL?
Ans. tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command note. 
Q. What are some good ideas regarding user security in MySQL?
Ans. There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet). There are as few users as possible (in the ideal case only root) who have unrestricted access.
Q. Explain the difference between MyISAM Static and MyISAM Dynamic. ?
Ans. In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
Q. What does myisamchk do?
Ans. It compressed the MyISAM tables, which reduces their disk usage.
Q. Explain advantages of InnoDB over MyISAM?
Ans. Row-level locking, transactions, foreign key constraints and crash recovery.
Q. Explain advantages of MyISAM over InnoDB?
Ans. Much more conservative approach to disk space management – each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
Q. What are HEAP tables in MySQL?
Ans. HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
Q. How do you control the max size of a HEAP table?
Ans. MySQL config variable max_heap_table_size.
Q. What are CSV tables?
Ans. Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed. 
Q. Explain federated tables. ?
Ans. Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
Q. What is SERIAL data type in MySQL?
Ans. BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT 
Q. What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
Ans.It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
Q. If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table?
Ans. 999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits. 
Q. What happens if a table has one column defined as TIMESTAMP?
Ans.That field gets the current timestamp whenever the row gets altered.
Q. What Is PHP?
Ans. PHP is an open source, server-side, HTML-embedded web-scripting language that is compatible with all the major web servers (most notably Apache). PHP enables you to embed code fragments in normal HTML pages code that is interpreted as your pages are served up to users. PHP also serves as a “glue” language, making it easy to connect your web pages     to server-side databases.
Q. What is PHP Variable and what is the rules of valid php variable.
Ans. 1.PHP variables are used to hold values or expressions.
2.A variable can have a short name, like x, or a more descriptive name, like carName.
3.Variables in PHP starts with a $ sign, followed by the name of the variable
4.The variable name must begin with a letter or the underscore character
5.A variable name can only contain alpha-numeric characters and underscores(A-z, 0-9, and _ )
6.A variable name should not contain spaces
7.Variable names are case sensitive (y and Y are two different variables)

Q. Is php a loosly typed language
Ans. In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.

Q. What is the difference between PHP4 and PHP5.

Ans 1. Object passing by value in PHP4 and by reference in PHP5
2. Class constants and static methods or properties
3. Visibility: public, protected and private
4. __construct() and __destruct(): before the contrustor had the same name as the class.
5. abstract classes. ++
6. Interfaces: an interface defines the methods a class must implement.
7. Magic methods like: __call, __get, __set and __toString;
8. Final keyword (even for a class, to prevent its children);
9. Autoload function: automatically load object files when PHP encounters a class that hasn’t been defined yet.
10. Type hinting – enforce what kind of variables are passed to functions or class methods – only for array and classes, not for scalars like strings or integers.
11. Exceptions: try-catch bloks.
12. E_STRICT Error Level
13. New functions and extensions

Q. What is php implode string function.
Ans. We can join all elements of an array and return a sting by using implode string function in PHP. Here are some examples
$ar=array(‘Welcome’,'to’,'plus2net’,'php’,'section’);
echo implode($ar);
The output is here
Welcometoplus2netphpsection
Sorry , we missed the space between words so let us add one gap between
$ar=array(‘Welcome’,'to’,'plus2net’,'php’,'section’);
echo implode(” “,$ar);
The output is here
Welcome to plus2net php section

Q. What is php explode string function.
Ans. We can break a string and create an array out of it by using a delimiter. Here is its syntax array explode( delimiter, string-to-break, limit);We can specify the delimiter and 2nd parameter is the string we want to break and third parameter is optional by which we can fix the number of elements of the array. Let us try some examples.                             
         $str=”Welcome to plus2net php tutorial section”;
$ar=explode(” “,$str);
print_r($ar);
We have used one space as delimiter. The output is here
Array ( [0] => Welcome [1] => to [2] => plus2net [3] => php [4] => tutorial [5] => section )
We don’t want more than three elements to in the array then change the code like this.
$str=”Welcome to plus2net php tutorial section”;
$ar=explode(” “,$str,3);
print_r($ar);
Output is here
Array ( [0] => Welcome [1] => to [2] => plus2net php tutorial section )

Q. What is Md5 hash. 
Ans. Md5 hash: Encryption of a string md5 returns the hash of a string. This is used to encrypt strings and  particularly encrypting the passwords of the user. This function returns the encrypted string by using RSA Data Security Inc.
Let us try to learn how to use this function.
$str=”Hello”;
echo md5($str);
The output of the above code will be
8b1a9953c4611296a827abf8c47804d7

Q. What is ucwords string function.
Ans. Converting the first letter to upper case of every word. We can use php string function ucwords to change all first character of words present in a string to upper case or     capitalize the first letter of each word.
Here is the syntax
$output=ucwords($input_str);
You can see the output string is $output and input string is $input_str in the above example.
Now let us try with one example
Here is a string variable $str with some string inside it. We will use ucwords to capitalize first chars of    every words inside it.
$str=”welcome to plus2net.com. you can learn web programming here”;
$str=ucwords($str);
echo $str;
The output is here
Welcome To Plus2net.com. You Can Learn Web Programming Here

Q. What is ucfirst string function.
Ans. We can change first character of any string to upper case letter by using ucfirst() string function Here is an example
$ar=”welcome to plus2net php section”;
echo ucfirst($ar);
The output is here
Welcome to plus2net php section

Q. Differnce between print and echo.
Ans. You are unlikely to ever want to know this, however the difference is that print will return a value to let you know if the statement worked or not, whereas trying the same  thing with echo will result in error: For example
echo “Please don’t make me say it… \n”;
$you = print “Hello World!\n”;
echo “Returning $you”; //Returning 1, assuming the print worked
echo:-  – Is a command only. – Faster than print
print:- – Is a function. – It will return true(1) or false(0) or some values.

Q. Explain the differece between mysql connect and pconnect. 
Ans. The difference between connect() and pconnect, it is simply like a shop when u entering in shop you will open the door and take your iteam come out and close the door that is     called connect() in mysql the connection to the mysql database will be automatically closed when the script terminates. When the door of the shop is already opend and never  close it is called pconnect(), open a connection with mysql_pconnect(), the connection will not be closed and will “persist” for future use. Mysql_connect opens up a database  connection every time a page is loaded. mysql_pconnect opens up a connection, and keeps it open across multiple requests. Mysql_pconnect uses less resources, because it does     not need to establish a database connection every time a page is loaded. First, when connecting, the function would first try to find a (persistent) link that’s already open     with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the SQL server  will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).
Q. What is MVC
Ans. The MVC pattern separates an application in 3 modules: Model, View and Controller:
Model- The model is responsible to manage the data; it stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the  application.
View-  The view (presentation) is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some     popular web applications, like wordpress, joomla, …
  Controller- The controller handles the model and view layers to work together. The controller receives a request from the client, invoke the model to perform the requested     operations and send the data to the View. The view format the data to be presented to the user, in a web application as an html output.

Q. Explain the php session.

Ans. When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you  start the application and when you end. But on the internet there is one problem, the web server does not know who you are and what you do because the HTTP address doesn’t  maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is  temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a     unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user’s session with the server, allow you to start saving user information, and assign a UID for that user’s session.
Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
Retrieve session data
<?php
//retrieve session data
echo “Pageviews=”. $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data. 

Comments

Popular posts from this blog

Create Signature pad with save on database in php

Create Signature pad with save on database in php 1.create a folder images index.php ============   <!DOCTYPE >     <head>     <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />     <title>Signature Pad</title>     <script type="text/javascript" src="jquery-1.8.0.min.js"></script>     <script type="text/javascript"> $(document).ready(function () {     /** Set Canvas Size **/     var canvasWidth = 400;     var canvasHeight = 100;     /** IE SUPPORT **/     var canvasDiv = document.getElementById('signaturePad');     canvas = document.createElement('canvas');     canvas.setAttribute('width', canvasWidth);     canvas.setAttribute('height', canvasHeight);     canvas.setAttribute('id', 'canvas');     canvasDiv.appendChild(canvas);    ...

Get Google Calendar Event List in WordPress

<a href="https://console.cloud.google.com/apis/credentials">Get Your Api Credentials Here</a> <a href="https://calendar.google.com/calendar">Get your Calender ID</a> <?php include_once("wp-load.php"); function  get_calender_events() { $params = array(); /*Get current date*/ $current_date  = date('Y-m-d H:i:s'); /*Convert it to google calendar's rfc_format */ $rfc_format = date("c", strtotime($current_date)); $params[] = 'orderBy=startTime'; $params[] ='maxResults=100'; $params[] = 'timeMin='.urlencode($rfc_format); $url_param = ''; foreach($params as $param) { $url_param.= '&'.$param; } $calender_id = "calender_id"; $client_key =  "client_key"; $url = "https://www.googleapis.com/calendar/v3/calendars/".$calender_id."/events?key=".$client_key."&singleEvents=true".$url_param; $list_events = wp_remote_post($url, ...

WooCommerce Mini cart With Ajax

WooCommerce Mini cart //MINI CART SECTION   <div class="productdiv rightcart">                                                         <?php if ( ! WC()->cart->is_empty() ) : ?>     <ul class="woocommerce-mini-cart cart_list product_list_widget <?php echo esc_attr( $args['list_class'] ); ?>">         <?php             do_action( 'woocommerce_before_mini_cart_contents' );             foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {                 $_product     = apply_filters( 'woocommerce_cart_item_pro...