...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 8, 2012

wkhtmltopdf: how to use it?

Question by Adam Strudwick

I want to be able to generate and save a PDF version of a PHP page. I found out, on Stackoverflow, that the most recommended is wkhtmltopdf: http://code.google.com/p/wkhtmltopdf/

However, I don’t have any Shell or binary knowledge; I only know HTML and PHP.

Could anyone CLEARLY guide me on how to get a php page generate a PDF document using wkhtmltopdf (using only FTP and PHP)?

Answer by Starx

I recommend reading their project page. Specially their usage wiki and php integration part,

Read more

PHP failing to show error messages

Question by Sergei

I wrote some code as a start for a username and password registration page but i cant get the first bit to work. The page with the forms corresponding to the variables at the top work fine but when redirected to this page it just gives a blank white page.

I seem to get this error every time i write some code that is not just basic echo or something like that… Can someone tell me what is wrong with the code and is there any good php editor where you can see error messages or somethilng like that?

This is not the first time i get the same blank page error and i would love to know what i’m doing wrong.

<?php
$user = $_POST["username"];
$pass = $_POST["password"];
$conf_pass = $_POST["conf_password"];

$con = mysql_connect("localhost", "webuser1", "12345");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}

if($pass != $conf_pass) {
  echo ("passwords don't match, <a href="./reg_form.php">return</a>");
}



mysql_close($con);

?>

Answer by MrCode

A blank white page often indicates a 500 Internet Server Error, which usually means you have a syntax or other error in your code.

In your case the error is in the quotes, try changing to:

 echo ("passwords don't match, <a href='./reg_form.php'>return</a>");

I suggest turning on error reporting in your code, or you can check your error log, this will tell you what the problem is and the line number.

error_reporting(E_ALL);
ini_set('display_errors', '1');

Also, if using Firebug, you can see the 500 Internal Server Error on the Net tab.

Answer by Starx

There are errors occurring on your code. To see what error is being generated. Use this command on the top of your page.

error_reporting(E_ALL);
Read more

PHP Redirect Within website

Question by baburao113

I’ve been trying this code since 3 days in a row until a certain time (minutes or seconds) but unable to solve the problem.

My target is to redirect visitor to 10 random URLs which are being selected from a text file. The user will see a certain page for a certain time and then redirect to another page again, the number of pages he will be redirected to is complete RANDOM.

PROBLEM:

The problem is the visitor is not being redirected to any other page which is randomly selected from a text file, instead it is just refreshing the page… But I want to redirect him to other pages from the text file.. Hope you guys understood me by now.

EDIT: Found the problem. Actually the $rand_link is having NULL as it’s value.. { [0]=> NULL } Don’t know why…. ANy solution? Checked the ‘BBnormalLinks.txt’ file for it’s permissions and that file is having some links in it for sure because I just checked it..

Thanks,

Here is the CODE:

<?php // Generate Random Nubmers.. 2 ********
            $numbers2 = range(13,70);

            shuffle($numbers2);

            for ($j=0;$j<1;$j++)
            {
            $numbers2[$j];
            }
                $seconds = numbers2[0];

            //////// For Random URL of Site
            $links = file('BBnormalLinks.txt');
        $rand_link = $links[ mt_rand(0, count($links) - 1) ];                   

                header("refresh:". $seconds .";url=". $rand_link); ?>

Answer by Starx

The syntax is correct but some pointers that can cause this are

  1. Some text have been outputted before the header is passed.
  2. The random page, is not being generated, thus ending up refreshing the same page again and again.

I have a very strong feeling, that your $rand_link is returning blank or null.


Update:

After a few discussion, the problem was the evil path again.

$links = file('patotofileBBnormalLinks.txt');

As baburao113, quoted

I had to move that file to wordpress theme folder lol! Problem resolved 🙂

Read more

xml to php table alternating row color

Question by bignow23

Trying to display an html table from and xml from php, getting error when trying to alternate the row base on even and odd mostly for styling the table.

foreach($bookdata as $book) // loop through our books
{
$i = 0;
        if($i%2 == 0)
   {
      $class = 'even';
   }
   else
   {
      $class = 'odd';
   }

  { 


        echo <<<EOF
        <tbody>
     <tr class='$class'>
                <td>{$book->date} </td>

                <td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
               <td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>


      </tr>
    }
       $i++;
    }


EOF;
}
 echo '</tbody>';
echo '</table>';

Any help most welcome

Answer by Starx

You are reseting the $i to 0 on every loop.

Remove

$i = 0;

from your code. And I didn’t notice this before but the EOF is misplaced. Here is a full working solution

foreach($bookdata as $book) // loop through our books
{
    if($i%2 == 0) { $class = 'even'; }
    else { $class = 'odd'; }
    echo <<<EOF
        <tbody>
            <tr class='$class'>
                <td>{$book->date} </td>
                <td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
               <td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>
            </tr>
EOF;
       $i++;
}
Read more

How to set vertical-align of span to middle of a div

Question by StevenChow

I test vertical-align with a simple html code, but it doesn’t work

<div style="height:45px; border: solid 1px black;">
    <strong style="vertical-align:bottom;">
        abc
    </strong>
</div>

Plz help me!

Answer by Starx

This is how you do it

<div style="height:45px; border: solid 1px black; display: table;">
    <strong style="vertical-align:bottom; display: table-cell;">
        abc
    </strong>
</div>

Demo

As I have mentioned before, vertical aligns are very tricky. For this to work, like it did on table, set the parent container to display as table and the inner <div>s or elements to display as table-cell

Read more

css tricks to shorten my redundant code

Question by Wondering Coder

I have an html that look like this:

<ul>
  <li>
    <img src="<?php echo base_url();?>assets/images/blue_background.png" class ="menu-bg"/>
    <a href="#" class="menu-portal"></a>
  </li>
  <li>
    <img src="<?php echo base_url();?>assets/images/blue_background.png" class ="menu-bg"/>
    <a href="#" class="menu-tags"></a>
  </li>
  <li>
    <img src="<?php echo base_url();?>assets/images/blue_background.png" class ="menu-bg"/>
    <a href="#" class="menu-requests"></a>
  </li>
  <li>
    <img src="<?php echo base_url();?>assets/images/blue_background.png" class ="menu-bg"/>
    <a href="#" class="menu-videos"></a>
  </li>
</ul>

As you can see the code above I kept repeating my blue background which in element img. Can anyone help me shorten this up. For example if I can insert the img in my li element, that would do.

Any help will be great.

Answer by Starx

Use it as a background, instead a defining a separate image tag.

ul li { 
   background-image: url("assets/images/blue_background.png");
   height: 30px; /* height of the image */
   width: 30px; /* width of the image if the size is fixed */
}
Read more

Making a button fixed on a changing DIV

Question by user1046671

Is there any way to allign a button to the center of the DIV.I was able to make it work with different strategies using a padding-top:2px and padding-bottom:2px or with using a margin-top and margin-bottom.But here comes the problem,basically it is a moving DIV i.e it might differ if the user have more inforamtion in it.For example user enters only work number in the input text field it will be showing up only the only work phone number.But if the user enters work,home and additional number,it need to show all the information entered,which will vary the size of the DIV.What happens is the div will increase in size and button still stays at the top of the div.Is there any way to make the button fixed at the center even after the DIV varies in size.Can it be achieved in CSS or we need to used javascript to make it work.

Answer by Starx

Vertical align is always tricky.

However where is a demo of moving centered button with CSS and moved with jQuery.

As it moves, the button remains at center as the position has not been defined.

#outer {
    text-align: center;
    width: 200px;  
    background: #ddd;
    height: 200px;
    position: static;
    display: table;
}
#inner {
    line-height: 200px;
    display: table-cell;
    vetical-align: middle;   
}
Read more

css sprites – a hover with images not loading correctly

Question by bryceadams

I have some css sprites on my site in the header but when the page loads it often loads several of the 8 separate images just below where it’s meant to be. Then I wait a few seconds or hover my mouse over them and it goes back to the correct positions.

Here’s my CSS:

.x {
display: inline-block }
.x a {
display:block;
width:100px;
height:100px;
overflow:hidden;}
.x a:hover img {
margin-left:-100px;}

and then the HTML goes like this:

<div class='x'><a href='link' alt='y'><img src=
'image' /></a></div> &nbsp;
<div class='x'><a href='link' alt='y'><img
src='image' />
</a></div>

for 8 separate 100×100 squares in a row.

Answer by Starx

The way to define css sprite is a bit different then how you are doing it.

Here is an example of how this can be achieved.

/* This is how to define a main image
.sprite { background: url("../link/to/spriteimage.png") 0px 0px; width: 32px; height: 32px; }

/* Assign an image like this way, by changing the position
.sprite.icon1 { background-position: -32px -32px; }
.sprite.icon1_hover { background-position: -64px -32px; }

Demo

Read more
March 7, 2012

What's wrong with this php foreach code? (merged array)

Question by Mouse Hello

$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);

            $items = 'SELECT items FROM menus';
            $itemLink = 'SELECT itemLink FROM menus';

            $itemQuery = $db->query($items);
            $linkQuery = $db->query($itemLink);

            $fetchItem = $itemQuery->fetch(PDO::FETCH_ASSOC);
            $fetchLink = $linkQuery->fetch(PDO::FETCH_ASSOC);

            $merged = array_merge($fetchItem,$fetchLink);

            foreach($merged as $key=>$value){
                echo "${key} =>  ${value} <br />";
            }

This is what it looks like in the database:

items   |itemLink
----------------------
Kill Bill|Kill Bill link
Preman  |Preman link

So, the expected output, or at least what I thought must be this:

    items => Kill Bill
    items => Preman
    itemLink => Kill Bill Link 
    itemLink => Preman Link

But the resulted output from the code is this:

items => Kill Bill
itemLink => Kill Bill Link 

It’s missing the other items and itemLink

So, how do I achieve the output that I want?

Answer by Sirko

        $fetchItem = $itemQuery->fetch(PDO::FETCH_ASSOC);
        $fetchLink = $linkQuery->fetch(PDO::FETCH_ASSOC);

This only fetches the first row of each resultset. You need fetchAll:

        $fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
        $fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);

and adjust the rest of your code.

        foreach($merged as $entry) {
          foreach( $entry as $key => $value ) {
            echo "${key} =>  ${value} <br />";
          }
        }

EDIT:
The call of fetch only retrieved the first row of the resultset, whereas fetchAll parses the complete resultset into an Array. So the Objects look like this afterwards:

Array(
  [0] => { 'items' => 'Kill Bill' },
  [1] => { 'items' => 'Preman' }
)
Array(
  [0] => { 'itemLink' => 'Kill Bill' },
  [1] => { 'itemLink' => 'Preman' }
)

array_merge concatenate both arrays to the following:

Array(
  [0] => { 'items' => 'Kill Bill' },
  [1] => { 'items' => 'Preman' },
  [2] => { 'itemLink' => 'Kill Bill' },
  [3] => { 'itemLink' => 'Preman' }
)

So we now have a two dimensional array. To traverse the values we need first to select each $entry, which is done in the outer foreach and can afterwards access the key/value structure in the inner foreach.

As pointed out in the other comment: If you want to preserve the connection between itemsand itemLink, you should change the query in the first place to

SELECT items, itemLink FROM menus

Answer by Starx

You can use simple array_combine() function to do what you are trying to do now.

$merged = array_combine($fetchItem, $fetchLink);

This will make all the item from $fetchItem as keys to the item from $fetchLink.

Read more

PHP String – Escape Single Quotes (for jQgrid Select Box)

Question by FastTrack

I have a string:

$departmentList = "value:'16:NAR,JR'S OFFICE;17:MFR'S OFFICE;18:NAR/MFR JOINT OFFICE'"

My problem is, the single quotes you can see in JR'S OFFICE and MFR's OFFICE are prematurely ending my string. I could switch my double quotes with single quotes and vice versa, but these are coming from user-entered values. If the user had entered a double quote, I would be in the same boat as I am now.

Any ideas on how to keep the integrity of this string while having single and double quotes throughout?

By the way, not sure if this matters for anything but – I’m putting my $departmentList string into a jQGrid to build the values for a select box.

Answer by xato

Use addslashes to replace " with " and ' with '.

Answer by Starx

If you are using the input for database purpose better use mysql_real_escape_string()

$departmentList = "value:'16:NAR,JR'S OFFICE;17:MFR'S OFFICE;18:NAR/MFR JOINT OFFICE'";
$data = mysql_real_escape_string($departmentList);
Read more
...

Please fill the form - I will response as fast as I can!