...

Hi! I’m Starx

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

Allow images in a <div> to be wider than lines of text in the same <div>

Question by Horace Loeb

I want to fit text in a <div> to the width of the <div>, but fit images in the same <div> to the width of the parent <div>

This diagram should make things clear:

(here’s the URL if it’s too small: http://dl.dropbox.com/u/2792776/screenshots/2012-01-22_1838.png)

Answer by Starx

With a little bit of js, you can do this with avoiding all the complication.

$(document).ready(function() {
    //read every images
    $("img").each(function(k,v) {
        //get the width parent's parent
        var width = $(this).parent().parent().innerWidth();
        //use it
        $(this).css('width',width);
    });
});

Demo

Read more
March 8, 2012

Background image of a li under the background image of the ul

Question by Jarco

How can you do this in css?
I want the background image of the li’s to slide under the background image of the ul where they are in.
I tried to do it with z-index but it didn’t work.

li{
list-style:none;
background-image:url("2.png");
z-index:-10;
position:relative;
}
ul{
    background-image:url("1.png");
    background-repeat: no-repeat;
    z-index:100;
    position:relative;
}

Is this possible? And how is it done if it is.

update: Picture explaining what i mean
css menu picture

Answer by Starx

I like the idea so much I just made it for you jarco. It seems it is not as exact as you want but, it is pretty similar.

Demo


A little div to show the bar, and script to bring it up and down

$("ul").mouseenter(function() {
    $("#bar").animate({
        height: $("ul").height()
    });
}).mouseleave( function() {
    $("#bar").animate({
        height: 20
    });
});

Update with the heights

Read more

Ajustment of Border in CSS

Question by sandbox

I want a border of Div to be less than the width of div. How to implement that in CSS?

Following image will give you more Clarity:

http://imageshack.us/photo/my-images/440/divkr.jpg/

Answer by Curt

This is not possible with plain CSS.

You could however use two div’s to get this effect.

<div class="outer">
<div class="inner">

    text

</div>
</div>​

.outer
{
    background-color:blue;
padding:20px;
    width:200px;
}

.inner
{
    border:solid 1px white;
    height:150px;
    color:white;
}


http://jsfiddle.net/RreTH/

http://jsfiddle.net/RreTH/1/

Answer by Starx

That is not possible.

Border is always the outside of element’s box model. However there might be a workaround you would like.

<div>
   <div id="inner" style="border:5px #000 solid;">
   </div>
</div>

Now, in this example, the border of #inner, will never exceed that of the parent.

As for the demonstration part, check this.

You will notice, the outer div has a thin red line to mark its border, but the inner div’s border can act as outer div‘s inner border.

Hope it helps

Read more

Simple php if !empty-function

Question by Jörg Mayer

I want to simply echo a link (set in a custom field in WordPress), when the corresponding field is not empty.

I tried the following, but the output is missing the link. Only the field as plain text gets printed

<?php $projekt_link = the_field('link');                                    
  if(!empty($projekt_link)){                                              
    echo '<a href="'.$projekt_link->name.'" class="button">Zum Projekt</a>';
  }
?>

Answer by Starx

If you are using the Advance Custom Fields plugin, then the correct syntax is

$projekt_link = get_field('link');
Read more

How to skip a statement execution from the second time if I call the same page again in PHP

Question by AshokiPhone

In my temp_file.php i have a variable (array)

<?php
 $temp = array();
?>

No in my currentPage.php i am using this

<?PHP
   include 'temp_file.php';
   ///giving some value to $id and calling same page again
   array_push($GLOBALS['temp'],$id);   
?>

I want to use this temp array to append a value each time i call the same file(CurrentPage.php) but include ‘temp_file.php’; statement is executing every time and i am getting single element to my array that i was last pushed.

Can any one help me is there any way in php to skip this include statement from second time to till the session end.

Answer by Starx

None of the answers are correct.

include_once() will not work for you, as you will be loading the page again, even if it is the second time, as with every load the php will execute from the top.

Because include_once() will only stop the redundant inclusion in same execution, not multiple.

Here is a simple workaround to your problem

<?PHP
   if(!isset($_SESSION['include']) || !$_SESSION['included'])) {
   // ^ Check if it was included before, if not then include it
       include 'temp_file.php';
       $_SESSION['included'] = true; //set a session so that this part never runs again for the active user session
   }
   ///giving some value to $id and calling same page again
   array_push($GLOBALS['temp'],$id);   
?>
Read more

Convert auto increment ID to 9 digit random serial number

Question by dotmlj

I have a MySQL database with users. Every row has an unique auto increment ID (1,2,3…). Now I need to convert this to a unique and random looking serial number that I can convert back to the ID – all using PHP.

User ID’s go from 1 to 99999999999 (INT(11)).

All serial numbers should have a minimum of 9 digits and never start with a 0.
Users should not easily be able to figure out how to guess a working serial number.

Thank’s 🙂

Answer by Ishtar

You could do some simple ‘encryption’. Take a (‘secret’) prime p 27407 and base 17 (for example). Compute the multiplicative inverse inv of base mod p-1, 12897. wolframalpha can do that for you.

Id to serial number

serial = id^base mod p
serial = 42^17 % 27407 = 24978

Serial to id

id = serial^inv mod p
id = 24978^12897 % 27407 = 42

This can be calculated quickly by exponentiation bysquaring. Only ids between 0 and 27407 can be used, (if not enough take a bigger prime number) and all have a unique invertible serial number.

To increase obscurity you can XOR the result with some value.

It’s not real cryptography, just stupid security through obscurity, but will take most humans quite some effort to crack.

Answer by Starx

I will not recommend doing what you are trying to do.

You see, autoincrement are generally done to represent to constantly avoid redundant data and still maintain readability.

So, instead update your database structure to store hash as well. The structure might be somethign like id, hash, name and so on.

In the hash, you can use any logic

$hash = sha1("secretanswer".$userid);
$trimmedhash = substr($has,0,9); //get a 9 digit random hash

Hashes are one way encryption and it is so for a reason also. Anyways, in order to verify the hash, you can do the same algorithm again

   $userid = "getthissomehow";
   $hash = sha1("secretanswer".$userid);
   $trimmedhash = substr($has,0,9);

   $prevhash = "asfaf23rfs"; //get previously stored hash somehow
   if($trimmedhash == $prevhash) { 
     //valid
   }
Read more

How to retrieve value from a select box?

Question by user782104

In html code:

<select name="123023d">
 <option value="default">Not Share</option>
 <option value="read">Read Only</option>
 <option value="edit">Editable</option>
</select>

In php code:

$rights=$_POST['123023d'];

Why i can not retrieve the value of this select box?

Notice: Undefined index: 123023d in C:xampphtdocsfyplistadd.php on line 87

Thank you.

I am sure it is in the form and it is a post method. It is located after foreach ($result as $set) as you can see i draw some sql value to generate that select box and the name of the select box is userID

Whole part:

<form id="addlist" method="post" action="add.php" >
<h1>Create your new subscriber list</h1> 
<p>Create a new list before adding subscriber <label class="right"><em class="dot">*</em> indicates required</label></p>

<label><em class="dot">*</em> List name:
<span class="small">Add your list name</span>
</label>
<input id="lname" name="lname" class="required" />

<div class="spacer"></div>

<label>Reminder:
<span class="small">Remind the details of your list</span>
</label>
<textarea id="creminder" name="creminder" cols="52" ></textarea>

<div class="spacer"></div>


<div class="spacer"></div>

<p>Email me when ...</p> 
<label>People subscribe:</label> <input type="checkbox" class="checkbox" name="subscribe" value="1">
<label>People unsubscribe:</label> <input type="checkbox" class="checkbox" name="unsubscribe" value="1">
<div class="spacer"></div>
</div>

</br>

<div id="stylized" class="myform">

<p>Permission Setting ...</p>

<label>Open to other users:</label> <input type="checkbox" class="checkbox" name="public" value="1">
Or
<div class="spacer"></div>

Select the permission for individual user:

<?
$sql =
    "SELECT  UserID,Name,Rights,Position
    FROM     user
    WHERE UserID != ?
    AND Rights != 'Admin'
    ";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));

$num_rows= $stmt->rowCount();

if ($num_rows != 0){
$result = $stmt->fetchAll();
?>

<table width="100%" class="display" id="viewSub">
<thead>
<tr>
<th field="col1" width="40%">Name:</th>
<th field="col2" width="40%">Position:</th>
<th field="col2" width="20%">Permission:</th>
</tr>
</thead>
<tbody>
<?
foreach ($result as $set) 
{
    echo "<tr><td>".$set['Name']."</td><td>".$set['Position']."</td><td><select name=".$set['UserID']."><option value='default'>Not Share</option><option value='read'>Read Only</option><option value='edit'>Editable</option></select></td></tr>";
}
?>
</tbody> 
</table>

<?
}
else
echo "There is no another user in this system";
?>


<input class="submit" type="submit" name="submit" value="Submit"/>
<div class="spacer"></div>

</form>

add.php which is the form and the result process

<?
include("../connection/conn.php");
session_start();

if($_SERVER['REQUEST_METHOD'] == "POST"){
print_r($_POST);
exit();
if (!isset($_POST['subscribe']))
$_POST['subscribe']=0;
if (!isset($_POST['unsubscribe']))
$_POST['unsubscribe']=0;
if (!isset($_POST['public']))
$_POST['public']=0;

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);



try {

    $listName = $_POST['lname'];
    $listRemindSub = $_POST['subscribe'];
    $creator = $_SESSION['username'];
    $listRemindUnSub = $_POST['unsubscribe'];
    $isPublic = $_POST['public'];
    $listReminder = $_POST['creminder'];


    $query="INSERT INTO list (ListID,ListName,Creator,IsRemindSub,IsRemindUnSub,IsPublic,CreateDate,Reminder) VALUES ('',?,?,?,?,?,CURDATE(),?)";
    $stmt = $conn->prepare($query);


    $stmt->bindParam(1, $listName , PDO::PARAM_STR);
    $stmt->bindParam(2, $creator, PDO::PARAM_STR);
    $stmt->bindParam(3, $listRemindSub, PDO::PARAM_INT);
    $stmt->bindParam(4, $listRemindUnSub, PDO::PARAM_INT);
    $stmt->bindParam(5, $isPublic, PDO::PARAM_INT);
    $stmt->bindParam(6, $listReminder, PDO::PARAM_STR);

    $stmt->execute();


}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="add.php"> Back</a>'); 
    $conn->rollBack();
    }


try {
    $lastID=$conn->lastInsertId();
    $query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'Email','{email}')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'FirstName','{fname}')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'LastName','{lname}')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="add.php"> Back</a>'); 
    $conn->rollBack();
    } 

try{
$sql = '
SELECT UserID
FROM user
WHERE Rights != ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array('admin'));
$result= $stmt->fetchAll();
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="add.php"> Back</a>'); 
    }

foreach ($result as $set)
{   
if ($set['UserID']==$_SESSION['username'])
$rights='edit';
else
{$rights=$_POST[$set["UserID"]];
$rights=$_POST['123023d'];}



if ($rights != 'default' || $set['UserID']==$_SESSION['username'] || $_POST['public']==0)
{ 
$user=$set['UserID'];
try {
    $query="INSERT INTO user_list(UserID,ListID,UserRights) VALUES ('$user',$lastID,'$rights')";
    $stmt = $conn->prepare($query);
    $stmt->execute();

}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="add.php"> Back</a>'); 
    $conn->rollBack();
    }  
}
}

$conn = null;

?>
<div id="stylized" class="myform">
<div style="text-align:center;font-weight:bold;">You have created a list. By default Mail Address, First Name , Last Name is in your list. Add more field if you want. <a href='add.php'>Back</a></div>
<div class="spacer"></div>
</div>
<?
}else{?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<style type="text/css">
      @import "../plugin/easyui/themes/default/easyui.css";
      @import "../plugin/easyui/themes/icon.css";
      @import "../style/form.css";
      @import "../plugin/datatable/media/css/demo_page.css";
      @import "../plugin/datatable/media/css/demo_table.css";
</style>
<script src="../plugin/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="../plugin/easyui/jquery.easyui.min.js"></script>
<script src="../plugin/jquery.validate.min.js"></script>
<script type="text/javascript" src="../plugin/datatable/media/js/jquery.dataTables.js"></script>
<script src="../plugin/jquery.form.js"></script>


<script>
$(document).ready(function(){
$("#addlist").validate();
});


$(document).ready(function() {
    $('#viewSub').dataTable();
    } );
</script>

</head>
<body>
<div id="stylized" class="myform">
<form id="addlist" method="post" action="add.php" >
<h1>Create your new subscriber list</h1> 
<p>Create a new list before adding subscriber <label class="right"><em class="dot">*</em> indicates required</label></p>

<label><em class="dot">*</em> List name:
<span class="small">Add your list name</span>
</label>
<input id="lname" name="lname" class="required" />

<div class="spacer"></div>

<label>Reminder:
<span class="small">Remind the details of your list</span>
</label>
<textarea id="creminder" name="creminder" cols="52" ></textarea>

<div class="spacer"></div>


<div class="spacer"></div>

<p>Email me when ...</p> 
<label>People subscribe:</label> <input type="checkbox" class="checkbox" name="subscribe" value="1">
<label>People unsubscribe:</label> <input type="checkbox" class="checkbox" name="unsubscribe" value="1">
<div class="spacer"></div>
</div>

</br>

<div id="stylized" class="myform">

<p>Permission Setting ...</p>

<label>Open to other users:</label> <input type="checkbox" class="checkbox" name="public" value="1">
Or
<div class="spacer"></div>

Select the permission for individual user:

<?
$sql =
    "SELECT  UserID,Name,Rights,Position
    FROM     user
    WHERE UserID != ?
    AND Rights != 'Admin'
    ";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));

$num_rows= $stmt->rowCount();

if ($num_rows != 0){
$result = $stmt->fetchAll();
?>

<table width="100%" class="display" id="viewSub">
<thead>
<tr>
<th field="col1" width="40%">Name:</th>
<th field="col2" width="40%">Position:</th>
<th field="col2" width="20%">Permission:</th>
</tr>
</thead>
<tbody>
<?
foreach ($result as $set) 
{
    echo "<tr><td>".$set['Name']."</td><td>".$set['Position']."</td><td><select name=".$set['UserID']."><option value='default'>Not Share</option><option value='read'>Read Only</option><option value='edit'>Editable</option></select></td></tr>";
}
?>
</tbody> 
</table>

<?
}
else
echo "There is no another user in this system";
?>


<input class="submit" type="submit" name="submit" value="Submit"/>
<div class="spacer"></div>

</form>
<div class="spacer"></div>
</div>
<br><br><br>
<div id="stylized" class="myform">
<?
try{
$sql = '
    SELECT   *
    FROM     list,user_list
    WHERE    user_list.UserID=?
    AND list.ListID=user_list.ListID
';
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$result= $stmt->fetchAll();
$num_rows= $stmt->rowCount();
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="add.php"> Back</a>'); 
    }
$conn = null;
if ($num_rows == 0) {
    echo '<div style="text-align:center;font-weight:bold;">You have not created any list yet.</div>';}
else {
    echo '<h1>Your Subscriber List</h1> <p>You have created '.$num_rows.' list(s).</p>';
foreach ($result as $set) 
{
echo '<div style="font-weight:bold;">List Name : '.$set['FromName'].'</div><br>';
echo '<div style="font-weight:bold;">Subscriber : </div><br>';
echo '<div style="font-weight:bold;">Create Date : '.$set['CreateDate'].'</div><br>';
echo '<hr>';
}}
    ?>
<div class="spacer"></div>
</div>
</div>
</body>

</html>

<?
}
?>

Answer by Starx

Note the method you are using to submit the form. There are two general ways

  1. GET Method <form method="GET" ... >

    This is generally retrieved by using

    echo $_GET['123023d'];
    
  2. POST Method <form method="POST" ... >
    This is generally retrieved by using

    echo $_POST['123023d'];
    

If no method is defined, by default, it will be submitted using GET method so, use

$rights=$_GET['123023d'];

Update

I found your problem, there is no quotes in the title of select box

<select name=".$set['UserID'].">

Change it to this. You have to provide the quotes and escape them as well.

<select name="".$set['UserID']."">

Update 2

Credit to @zerkms

The another problem was starting the name with a numeric value instead of a alphabetically character.

<select name="123023d">

Make sure you dont start with numbers like

<select name="a123023d">
Read more

wrapping a function as a jQuery parameter

Question by Joseph the Dreamer

i am buliding an autocomplete for my website when i came across this style of building code:

$(function() {

    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $(element).autocomplete(....

    //more code
});

i know about closures, “IIFE”s but this one’s a new one for me.

  • what’s with the “jQuery-wrapped” code above?
  • is there any particular reason i should do that? (scope?)
  • optimization-wise, should i even do it that way?

Answer by Starx

  1. $(function() { }); is equivalent to $(document).ready(function() {}); and as before it executes once the DOM has been ready.

  2. Defining a function inside is to tell that, the function is only available once the dom is ready to execute.

  3. $(element).autocomplete(.... is simply implementing the plugin to the selector, once the DOM is ready to execute.

Hope its clear now 🙂


$(function() { or $(document).ready(function() { does not need the whole page to load, to run as $(window).load(fn) does.

Read more

Uninstall PHP completely from Ubuntu

Question by user1162039

could some one tell me how to uninstall PHP completely from Ubuntu?? I have problems with installing MySql because of this. They seem to have some unmet dependencies. I think I messed up with the whole installation procedure :(, could some one help me with this problem? Thanks you 🙂

Answer by Starx

This is not a easy way to answer. First we have to know how to installed the PHP at first place.

But for every way, this must work.
Search what kind of package you have installed using

aptitude search php5

and remove them accordingly using purge command

sudo aptitude purge php5-package1 ...so on
Read more

resizable on text area element not working

Question by Goldy

i have started to learning Jquery and i can’t activate the resizable function.
i downloaded the core Jquery and the UI.

all working well, the animate,scroll,effects and more

BUT the resizable functions kinda stack and i have no idea why.
i have been marked the resizable pack and check if the UI have it and its have.

i try to activate it in safari , chrome ,ff on the latest versions .

<script type="text/javascript" src="../scripts/Jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../scripts/Jquery/jquery-ui-1.8.18.custom.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() 
    {
        /*not working , we need to check why its not readable.*/
        $('p').resizable('enable');

        $('textarea').resizable({
            handles: "se",
            grid : [20, 20],
            minWidth :153,
            minHeight :100,
            maxHeight :200,
            containment: 'parent'
        });
    });
</script>

Answer by Ngalam City

if you’ve loaded all ??

try it :

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
    #resizable { width: 100px; height: 100px; background: silver; }
  </style>
  <script>
  $(document).ready(function() {
    $("#resizable").resizable();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="resizable"></div>

</body>
</html>

Answer by Starx

Where is your handles? Try to see if this works

  $('textarea').resizable({
  handles: "se",
  grid : [20, 20],
  minWidth :153,
  minHeight :100,
  maxHeight :200,
  containment: 'parent'
  });

Here is a demo of your code working. Be sure to include the CSS File, in order to see the handle.

Read more
...

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