mysqli (MySQL Improved)

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

– Object-oriented interface

– Support for Prepared Statements

– Support for Multiple Statements

– Support for Transactions

– Enhanced debugging capabilities

– Embedded server support

$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
if (!$res) {
die('There was an error running the query [' . $db->error . ']');
}
$row = $res->fetch_assoc();
echo $row['_msg'];

echo 'Total results: ' . $res->num_rows;

$statment = $db->prepare("SELECT `name` FROM `users` WHERE `username` = ? and `age` = ?");
$statement->bind_param('si', $name, $age);
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
}

In bind param, first parameter denotes the types “s for string, i for integer, d for decimal, etc)

http://codular.com/php-mysqli

PHP Data Objects & Prepared Statements

PDO provides a data-access abstraction layer, which means that, regardless of which database you’re using, you use the same functions to issue queries and fetch data.

try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "
";
die();
}

// Persistent Connections
true
));
?>

Prepared Statements :
They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
a) The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters.
b) The parameters to prepared statements don’t need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// repeated inserts
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// fetching data
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}

PDO vs mysqli :
While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements.

PDO works with several databases whereas MySQLi works with MySQL only.

PDO has named parameters whereas MySQLi does not.
$pdo->prepare(‘SELECT * FROM users WHERE username = :username AND email = :email’);
$params = array(‘:username’ => ‘test’, ‘:email’ => $mail);

$mysqli->prepare(‘SELECT * FROM users WHERE username = ? AND email = ?’);
$query->bind_param(‘test’, $mail);

http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-should-you-use–net-24059

System Design

1) “Design and code a system that can accept millions of events in real time and report the number of events for the last 10 minutes (sliding window). The system has to account for performance and concurrency.”

http://www.glassdoor.com/Interview/Design-and-code-a-system-that-can-accept-millions-of-events-in-real-time-and-report-the-number-of-events-for-the-last-10-mi-QTN_187032.htm

2) Design a URL shortner service :

http://www.hiredintech.com/app#the-system-design-process

3) Design a unique id service like youtube
http://kvz.io/blog/2009/06/10/create-short-ids-with-php-like-youtube-or-tinyurl/

4) Design an Elevator System and give the objects involved and their interactions.

http://www.careercup.com/question?id=1808669

Binary Tree Algorithms

1) Find deepest node of a binary tree
(Karumanchi, pg 120)

2) Find height of a binary tree (recursion method)
(Karumanchi, pg 119 , with small correction)

3) Find height of binary tree (non recursion)
(Karumanchi, pg 120, with small correction)

4) Find Least Common Ancestor of 2 nodes in a binary tree
(Karumanchi, pg 126)
https://www.youtube.com/watch?v=13m9ZCB8gjw

5) Find Least Common Ancestor of 2 nodes in a binary SEARCH tree
(Karumanchi, pg 153)

6) Find Shortest path of 2 nodes in a binary SEARCH tree
(Hint: Find LCA and then calculate path from LCA to each node)

7) Determine if a Binary Tree is a Binary Search Tree
http://leetcode.com/2010/09/determine-if-binary-tree-is-binary.html
(Karumanchi : pg 155, prob 52)

8) Serialize and Deserialize a Binary Tree
http://www.geeksforgeeks.org/serialize-deserialize-binary-tree/
http://www.careercup.com/question?id=6228581160058880
http://leetcode.com/2010/09/serializationdeserialization-of-binary.html

8 b) Serialize and Deserialize a Binary Search Tree
https://www.youtube.com/watch?v=H594EV9OuDI
http://leetcode.com/2010/09/saving-binary-search-tree-to-file.html

9) Given a string of html tags like “< a >< b >< c >< /c >< d >< /d >< a >< /a >< /b >< /a >“, construct a tree where each node is like
Node { string tag, ArrayOfChildren[] };
Note that the tree need not be binary tree.
This was asked in SugarCRM.

 


BuildTree(root, parent) {
   tag = readTag(); // assume function readTag will output each tag serially 
   if (isOpenTag(tag)) {
       node = new Node;  // create a new Node
       node.tag = tag; 
       Stack.push(node); // push into stack 
       if (root == NULL) { 
           root = node;  
       } elseif (parent != NULL) {
           AddChild(parent, node);
           BuildTree(root, node);  // Build tree with node as parent 
       } else {
          // error
       }
   } else {
       temp = Stack.pop();
       if (Stack.NotEmpty()) { 
          parent = Stack.pop; 
          BuildTree(root, parent);  
       }
   }
   return root; 
}

What is ob_start in php ?

The PHP output buffering will save all the server outputs ( html and php prints) to a string variable.

So to start buffering, use ob_start(); this will keep saved any output.
Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

Here are few samples of the use of ob_start() and ob_get_clean()

ob_start(); //Turn on output buffering ?>
Hello world, link
Content
$var = ob_get_clean(); ?>
//copy current buffer contents into $message variable and delete current output buffer

Explain PHP namespaces

http://daylerees.com/php-namespaces-explained

Previously in PHP you can’t have two classes that share the same name. They have to be unique. The issue with this restriction is that if you are using a third party library which has a class named User, then you can’t create your own class also called User. This is a real shame, because that’s a pretty convenient class name right?

PHP namespaces allow us to circumvent this issue, in fact we can have as many User classes as we like. Not only that, but we can use namespaces to contain our similar code into neat little packages, or even to show ownership.

Using a class declared in a namespace

Classes in Global namespace can also be referred as :

$eddard = new \Eddard();

Namespaces can have as many levels of hierarchy as they need to.

This\Namespace\And\Class\Combination\Is\Silly\But\Works

What are php Lambdas and Closures?

http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/

What is a Lambda?
A Lambda is an anonymous function that is can be assigned to a variable or passed to another function as an argument. Because the function has no name, you can’t call it like a regular function. Instead you must either assign it to a variable or pass it to another function as an argument.

Lambdas are useful because they are throw away functions that you can use once. Often, you will need a function to do a job, but it doesn’t make sense to have it within the global scope or to even make it available as part of your code. Instead of having a function used once and then left lying around, you can use a Lambda instead.

What is a closure ?
A Closure is essentially the same as a Lambda apart from it can access variables outside the scope that it was created.
// Create a user
$user = "Philip";

// Create a Closure
$greeting = function() use ($user) {
echo "Hello $user";
};

// Greet the user
$greeting(); // Returns "Hello Philip"

As you can see above, the Closure is able to access the $user variable. because it was declared in the use clause of the Closure function definition.

If you were to alter the $user variable within the Closure, it would not effect the original variable. To update the original variable, we can append an ampersand.

__autoload function in PHP

In PHP, the __autoload function is used to simplify the job of the programmer by including classes automatically without the programmer having to add a very large number of include statements. An example will help clarify. Suppose we have the following code:

include “class/class.Foo.php”;
include “class/class.AB.php”;
include “class/class.XZ.php”;
include “class/class.YZ.php”;

$foo = new Foo;
$ab = new AB;
$xz = new XZ;
$yz = new YZ;

Note in the code above that we have to include each of the 4 different class files separately – because we are creating an instance of each class, we absolutely must have each class file. Of course, we are assuming that developers are defining only one class per source file – which is good practice when writing object oriented programs, even though you are allowed to have multiple classes in one source file.

Imagine if we need to use 20 or even 30 different classes within this one file – writing out each include statement can become a huge pain. And this is exactly the problem that the PHP __autoload function solves – it allows PHP to load the classes for us automatically! So, instead of the code above, we can use the __autoload function as shown below:

function __autoload($class_name)
{
require_once “./class/class.”.$class_name.“.php”;
}

$foo = new Foo;
$ab = new AB;
$xz = new XZ;
$yz = new YZ;

Autoloading works like this. You create a function called __autoload() near the start of your PHP application. Then, whenever your code tries to create a new instance of a class that PHP doesn’t know about, PHP automatically calls your __autoload() function, passing in the name of the class it’s looking for. Your function’s job is to locate and include the class file, thereby loading the class. PHP can then go ahead and create the object.

spl_autoload_register
spl_autoload_register provides a way to define more than one __autoload function using spl_autoload_register. If you already have an __autoload function you will need to register that function before registering any additional functions though.
spl_autoload_register(‘__autoload’);
spl_autoload_register(‘my_other__autoload’);

Additionally, spl_autoload_register accepts any ‘callable’ type variable, meaning that you can use a method from a class as an autoload function as well.
//for a static method
spl_autoload_register(array(‘MyAlreadyLoadedClass’, ‘autoloader’));

Its recommended to use spl_autoload_register since __autoload may be deprecated in the future.

PHP: Example of the __autoload function