ShareThis

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, November 26, 2012

[PHP] Loop through files in directory and subdirectories

PHP has a lot of great functionality in its standard library. One helpful functionality is the RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator, which allows you to easily recurse over files in a folder structure (including sub-folders!).

First, create an instance of the RecursiveDirectoryIterator,with the parameter set to the path of your base directory you are inspecting.

Then, using a foreach loop,  use RecursiveIteratorIterator to inspect each file and do whatever logic you would like to on them.

Code:
<?php
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
} 
?> 
Not satisfied? You can find some alternatives to looping directories on StackOverflow.

Sunday, November 25, 2012

[PHP] Using Enums in PHP

PHP has no defined enums in its language, but there are easy ways of creating your own that are elegant, working solutions.

An enum can be mimicked using a class with constant values set to integers. Note: There are many ways of doing this. This is just one! At the bottom of the post is a link containing alternative solutions.


Code:
<?php

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

var $today = DaysOfWeek::Sunday;
?>

In this example the enum DaysOfWeek contains the constants Sunday and Monday. You could extend the code to use a switch case block in which the cases are stated like the $today variable:


Code:
<?php

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

var $today = DaysOfWeek::Sunday;

switch($today)
{
  case DaysOfWeek::Sunday:
  // do sunday logic
  break; 

  case DaysOfWeek::Monday:
  // Monday logic
  break;
}
?>

This is just one way of mimicking enums in PHP. Here are some other ways!

Sunday, October 28, 2012

[PHP] mysql select where in php array

Say you are given the following array of ids:


<?php 
 $vals = array
         (
           [0] => 1
           [1] => 2
           [2] => 5
         )
?> 


And you want to run a sql query to retrieve rows where the id is in this array.


<?php 
$ids = join(',' , $vals);  
$sql = "SELECT * FROM galleries WHERE id IN ($ids)"; 
?> 

Wednesday, October 24, 2012

[PHP] Get Unix timestamp of one week ago

This is super simple:

echo strtotime("-1 week");

It will show up like this:

1350507267  

Wednesday, October 3, 2012

[PHP] Passing PHP parameters from a jQuery Load

I was running into a uncaught exception, error with expression when trying to pass php parameters in a jquery .Load("file.php?a= ... " );

This was occurring because the parameter value for "a" contained spaces.

You can get around this easily with this little hack:

$("#itemwithtext").text().split(" ").join("%20");

This will get the text of the given element, split it into an array delimiting with spaces, then join the array together using the %20 space command, which can be passed safely.

Related solutions

Wednesday, September 26, 2012

[PHP] See if checkbox is checked in form post processing

Checking to see if a textbox is checked (Regardless of "value" attribute) is as simple as this:


if ( isset($_POST['mycheckbox']) )
{
   // checkbox was checked
}
else
{
  // checkbox was not checked
}

Monday, August 27, 2012

[PHP] Get working directory

In PHP, there is a very simple way to retrieve the working directory.

You simply call dirname(__FILE__ wherever it is needed. You can also stack dirnames to retrieve parent directories as shown in the example below:

<?php
 
//Example script path: home/content/en/script.php
 
$parentparentdir=basename(dirname(dirname(__FILE__)));
 echo 
$parentparentdir//will output 'content'

?>

Wednesday, June 27, 2012

[PHP] mysqli_num_rows not working

Not sure why this is happening, but my mysqli_num_rows was returning zero when it shouldnt.

My fix was to switch:

mysqli_num_rows($mysqli, $result)

with

$result->num_rows

That accesses the property of the query result num_rows, and works.

Monday, June 25, 2012

[PHP] Migrating from mysql_ to mysqli_

---------------------------------------------------------------------------------
This is a WIP blog post. I will continue updating it as I indulge in more mysqli.
-------------------------------------------------------------------------------

I now have the pleasure to show the process of moving from mysql_ to mysqli_. If you are still on mysql_, you will still be able to use mysql functionality. However, it is being depreciated and it is recommended to make the switch. You will get harassed on StackOverflow for suggesting mysql_* answers, or asking mysql_* questions.

The first change you will make will be the database connector.

Old Way
$connection = mysql_connect('host','user', 'pass');
mysql_select_db('yourDb');


New Way
$mysqli = new mysqli('host','user', 'pass','db');
if($mysqli ->connect_error)
{
   die('Failed: ' . $mysqli->connect_errno . ' ' . $mysqli ->connect_error);
}
The next bit I encountered was getting a query statement through. It would usually be as easy as this:

Old way:

$statement = mysql_real_escape_string('select * from myTable');
$result = mysql_query($statement);
The new way is a bit more complex:

1) Prepare your statement!
$statement = mysqli_prepare($connection, "SELECT name, weight, height FROM myTable WHERE id='".$id."'");
2) Execute your statement!
$statement -> execute();
3) Bind results to variables ! (The cool feature)

$statement -> bind_result($name, $weight, $height);

4) Store the results from the query.
$statement->store_result();
5) (optional) Need to check the row count?
$count = $statement->num_rows;
6) (optional) Need to access a specific row? 0 ?
$statement->data_seek(0);

7) Fetch results (can be done iteratively)
sample: 
$statement->fetch();
Now your binded variables are populated: check $name, $weight

That is a lot of calls for a simple query! You might like this instead:

You can use mysqli_real_escape_string, mysqi_query, mysqli_num_rows in the same manner as mysql_query, with ONE change to your code:
Old way:
<?php 
mysql_result("SELECT blog from TheBestBlogs where name='hazelfresh'"); 
?>
New Way: If using the procedural style as such, you must include the connection variable in your call. This holds true for all procedural calls with mysqli:
<?php 
mysqli_result($mysqli, "SELECT blog from TheBestBlogs where name='hazelfresh'"); 

if(mysqli_num_rows($mysqli, $mysqliResult)>0); 
$escapedWorld = mysqli_real_escape_string($mysqli, "hello world!");
?>
It is a pain to rewrite your queries this way if you use rows and column names: $result['id'] for example. Luckily, there is a way around that too for mysqli:

<?php

// ... document's example code:

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {

        // use your $myrow array as you would with any other fetch
        printf("%s is in district %s\n", $city, $myrow['district']);

    }
?>








Wednesday, June 20, 2012

PHP - Get current time in microseconds

http://php.net/manual/en/function.microtime.php

Same as time(), just use microtime();

Wednesday, June 13, 2012

Array Length PHP

To find the array length in PHP, you can use


count()

or


They are the same thing.

Example:

<?php
  $array = array();
  $array[0] = 1;
  $array[1] = 2;
  $size = count($array);
?>

Sunday, June 10, 2012

[PHP] Initialize empty array

Try:

$myArray = array();


Sunday, March 4, 2012

[FIX] PHP Header( ... ) opens page in Frame instead of new page

Issue: 
Trying to redirect using "header ( ... )"  in PHP. Instead youre getting it opened up in your iFrame

Example:


Fix: 
Add the following to your <a href="..." > links </a >
target="_top"
That'll do it!

[FIX] Failed to load resource: the server responded with a status of 403 (Forbidden)

Scenario: 

You're trying to grab some images in your html / php code that calls a css style sheet. Then youre running into this error in your browser console:
Failed to load resource: the server responded with a status of 403 (Forbidden)
I found that the problem was using the incorrect slashes for the image directory.

The Wrong Way:
"images\main\ico.png"
The Right Way
"images/main/ico.png"
Hope this helps. Didn't find any solutions online for the problem, but used some common sense to figure it out.

Wednesday, February 22, 2012

PHP Insert date as "mm/dd/yy"

Very simple code:

<?php
echo date("m/d/y");
?>

Tuesday, February 21, 2012

[SOLVED] XAMPP mysql Starts then Stops


Problem:
  • Trying to start MySql on Xampp on Windows 7
  • Mysql starts then stops or doesnt even start at all

Diagnosis: Mysql or a sql service may already be running on the given port, preventing mysql from starting.

Solution:

  1. Open Task Manager, and go to Services
  2. Navigate to "M" 
  3. Halt all mysql, mysql55 services that are running.
  4. Now start your mysql from Xampp!!