...

Hi! I’m Starx

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

PHP Transfer of variables from one page to another

Question by Daniel USAF

I got my first PHP form working, and it submits to the database before returning to the form. But the form does not reflect the submitted values. I remember how to inject dynamic HTML based on PHP variables, but my understanding is that first there is a way to transfer php variable values from one page to another. How do you do this? Here is the end of my submission page, just in case it helps.

$STH = $DBH->prepare("UPDATE administration SET ac1= ?, ac2= ?, fan= ?, na= ?, dh= ?, tolerance1= ?, temptime1= ?, tolerance2= ?, temptime2= ?, tolerance3= ?, temptime3= ?, tolerance4= ?, temptime4= ?, tolerance5= ?, temptime5= ?, humidtolerance1= ?, humidtime1= ?, humidtolerance2= ?,  humidtime2= ?, humidtolerance3= ?,  humidtime3= ?, humidtolerance4= ?,  humidtime4= ?, humidtolerance5= ?,  humidtime5= ? WHERE custnum = ?"); 
$STH->execute(array($ac1, $ac2, $fan, $na, $dh, $tolerance1, $temptime1, $tolerance2, $temptime2, $tolerance3, $temptime3, $tolerance4, $temptime4, $tolerance5, $temptime5, $humidtolerance1, $humidtime1, $humidtolerance2, $humidtime2, $humidtolerance3, $humidtime3, $humidtolerance4, $humidtime4, $humidtolerance5, $humidtime5, $custnum));


$STH->execute();  

//Send them back to the page they were at/
header("location:index.php");

Answer by Starx

Use super global variables to pass the data from one page to another. There are many but some of the most popular are:

  1. $_GET

    Pass the data in the form of url page.php?variable=value and
    read the values as `echo $_GET[‘variable’]

  2. $_POST

    Pass the data using <form method="POST">...</form>
    and read the values as echo $_POST['variable']

  3. $_SESSION

    1. Start the session session_start();
    2. Declare a variable $_SESSION['variable'] = "value";
    3. Read the value echo $_SESSION['variable'];
  4. $_SERVER

    1. Declare a variable $_SERVER['variable'] = "value";
    2. Read the value echo $_SERVER['variable'];

Each of the above methods are fit in their own cases. To read more go here.

Read more

Jumping to Position on page after Dynamic content added

Question by Cookiimonstar

I use ajax to dynamically add content to my site but i want the page to jump to the content has been added but i cant get i to work.

here is the link i am using to add the content and to jump the the position.

<a href="javascript:ajaxpage('/console/new_message_profile.php', 'message_area');" onclick="window.scrollTo(0, 2000);">

Answer by Starx

Give an id to the dynamically generated element and then

$("#idofdynamicelement")[0].scrollIntoView( true );
// O to make sure its the first item if multiple found
// true to indicate the top position
Read more

Setting Jquery Enter Key Event For Dynamically Generated TextBox

Question by irfanmcsd

How to set jquery keyup event for dynamically generated textbox instead of static text box as shown below?

$('#statictextboxid').keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
    alert('Enter key was pressed.');
}
});

Answer by Starx

Bind the event using .on() to keep it attached for dynamically generated elements also

//Simulate dynamically generated textbox
$("body").append("<input type='text' class='textbox' />");
// Now bind the event
$('.textbox').on('keyup', function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
    alert('Enter key was pressed.');
}
});

Demo with the simulated version

Read more

Show DIV > SPAN only when DIV > TABLE >TR is visible

Question by Saif Bechan

I have a layout that looks like this

<div class="categoery">
    <span>categorie title</span>
    <table>
        <tr class="item show">....</tr>
        <tr class="item show">....</tr>
        <tr class="item none">....</tr>
    </table>
</div>

<div class="categoery">
    <span>categorie title</span>
    <table>
        <tr class="item none">....</tr>
        <tr class="item none">....</tr>
        <tr class="item none">....</tr>
    </table>
</div>

Now what I want to the is the following. The first div will be the category title, and the two rows.

Now in the second div, I want the whole div completely hidden.

CSS has no parent seelctor like: div < tr.none{ display:none; }.

I asume another thing I can use is the hasClass from jQuery, but I was wondering if there is a pure CSS approuch.

==

Maybe something like setting the div to height:0, but block elements(tr) with a top margin will force the div to expand??

Hope this makes sense.

Answer by Starx

You can do something like this

$('.categoery').each(function(k,v) {
    if($(this).children('table').find("tr").css("display")=='none') {
    // alternate
  //if($(this).children('table').find("tr").hasClass("none")) {
        $(this).children('span').hide();
    }
});

I even created a demo. I hope this was what was asked for.

Read more

Send Variable from one html to another

Question by lucky13

I have 2 HTML pages, send.html and receive.html
In each page I have a textield. The thing that I’m trying to do is whenever the “value” of the textfield in the send.html changes, automatically parse the data to the textfield value of the receive.html. When I say automatically I mean without the need of a button or reloading the pages.

To sum up.. I have this textfiled in the send.html

<input type="text" id="send" size="25" value="Val1">

And this text field in the receive.html

<input type="text" id="receive" size="25" value="Val2">

I want to “monitor” somehow the Val1, and if it changes I want Val2=Val1

For my purpose I cant use jquery.
Is that possible?

Answer by Starx

I think you are missing a big picture. Data sending and receiving needs some server side interaction like using PHP, ASP, JSP, Python etc., unless you are ok with cookies.

When you update a field in one age, that data needs to go the server somehow for another page to catch. Either way, the way you want it to go automatic is not possible right now. However, I will provide a solution of how you can do this using jQuery and PHP. But if you want?


Update

So, it seems cookies is the only option. Follow the following steps

Create a new file cookie.js and place the following code inside

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^s+|s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

Next, create two html file “test1.html” and “test2.html” with this markup

<html>
<head>
    <script src="cookie.js"></script>
</head>
<body>
    <input type="text" id="text1" name="text1" />
</body>
</html>

Now, on test1.html add the following script on the head

<script>
    window.onload = function() {
        document.getElementById("text1").onchange = function() {
                                                  // ^ use onkeyup if you want this to occur as you type
            setCookie("shared", this.value, 1);
            alert('oK, val changed so lets check it');              
        };
    };
</script>

On Test2.html add the following Script on the head

<script>
    var checkandupdate = function() {
           var shared = getCookie("shared");
           if(shared) {

              document.getElementById("text1").value = shared;
           }
    };

    window.onload = function() {
        int = setInterval("checkandupdate()",1000);
    };

</script>

Now

  • Open both pages
  • Go to test1.html and type something then press tab to get the alert message.
  • Open the test2.html, it should be update within 1 second
  • After the demo works, Update the field names as you need

Enjoy 😉

Read more

Best way to handle positioning in a website

Question by user1173371

My positioning of certain items on my web page keep moving slightly when i develop them on a big screen and display on a small screen they are out of position slightly, and vice versa.

this never happened me before but this is also the first site i am developing in asp.net here’s my CSS

#backb{
  position:absolute;
  left :22%;
  bottom:10%;
 }

#backf{
  position:absolute;
  left :12%;
  bottom:0%;
 }

#avatar{
  position:absolute;
  left :55%;
  bottom:45%;
 }

Answer by Starx

There is no such thing as best positioning while designing a page. You should use the techniques that are cross compatible across browsers and different systems.

In your CSS, you are using

position: absolute;

While using this style the element is positioned relative to its first positioned ancestor element. So, by default, its position will be relative to that of <body>.

Next, you are using percentage(%) values of assigning the different positions of the elements. This values are calculated by browser with respect to first relatively positioned ancestor, which is also by default <body>, so every time the resolution changes the template will shift accordingly.


Now, some pointers from me.

  1. Do not use position:absolute unless its absolutely necessary.
  2. Using percentage% values always lead to fluids result, so if you don’t know how to handle it don’t use it.
Read more

How to login in MySQL with a Non Root user

Question by sandbox

I have setup 2 user Uone and Utwo in Mysql. But when I open localhost/phpmyadmin it logins with root user. What URL is used to login with Uone or Utwo user. I am running Mysql from XAMPP.

Answer by Starx

IF you had installed phpmyadmin separately, you would be asked for username and password in the startup.

Since you have a pre-installed version of phpmyadmin. You can do the following to do so.

  1. Find the phpmyadmin installation or project file
  2. Open the file called config.inc.php
  3. Inside you will find details to change the username and password ...

    $cfg['Servers'][$i]['user']          = 'Uone';
    $cfg['Servers'][$i]['password']      = 'cbb74bc'; // use here your password
    $cfg['Servers'][$i]['auth_type']     = 'config';
    
Read more

mysql select data from a multivalue attribute

Question by user962449

How can I run a select query on a multivalue attribute? Does mysql have a function do select certain data from a multivalue field? Much help is appreciated. Here’s a sample of the problem:

Table

userid      groups
-------------------
  2          2,3,5
  4          1
  9          2,5,10

datatype is char(250) for groups

I want to do a query to select all userids that belong to group 5, in this example it would be userid 2 and 9. So:

userid
------
  2
  9

Any way to go about it with a mysql query? or with php/mysql?

Answer by Starx

In case the groups datatype is SET

You can use

SELECT * FROM users WHERE FIND_IN_SET('5', groups);

UPDATE

In case of char or varchar. You can use this

SELECT * FROM users
WHERE 
     groups LIKE '5,%'
     OR groups LIKE '%,5'
     OR groups LIKE '%,5,%'
     OR groups = '5'
Read more
March 10, 2012

How to handle my data?

Question by Jack4

Edit: The aim of my method is to delete a value from a string in a database.

I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:

str_replace($pid . ",","",$boom);
  • $pid is a page id, eg 40
  • $boom is an exploded array

If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:

,56,12

When i have the concat in the str_replace it doesnt do a thing. So does anyone know if you can do this?

Answer by hakre

After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:

$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
    unset($boom[$r]);
}

Old question:

Can you concatenate inside a str_replace like this: … ?

Yes you can, see the example:

$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));

Result:

Array
(
    [0] => 56,12
)

Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.

It might be easier for you if you’re unsure to create a variable first:

$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));

Answer by Starx

As $boom is an array, you don’t need to use array on your case.

Change this

$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);

to

$together = str_replace($pid . ",","",$ticket_array);

Update: If you want still want to use array

$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
Read more

How can I consolidate this jquery code

Question by user1261582

I have navigation elements that add a class to the clicked link, and removes the class from the remaining links. How can I consolidate this easily into one function that recognizes which link is clicked and removes the class from the remaining links (or active link)

Heres code for one link – trying to avoid this for each link:

$("#work").click(function () {
    $(this).addClass('active');
    $("#about").removeClass('active');
    $("#testimonial").removeClass('active');
    $("#instruction").removeClass('active');
    $("#blog").removeClass('active');
    $("#contact").removeClass('active');
});

Thanks

Answer by James Aylett

I may be misunderstanding the question, but how about:

function mark_active() {
  $('a').removeClass('active');
  $(this).addClass('active');
}
$("#work, #about, #testimonial, #instruction, #blog, #contact").click(mark_active);

Answer by Starx

Considering, all the links are <a> and inside a parent lets say #menu.

var allchild = $("#menu").children("a");
allchild.click(function () {
   allchild.removeClass('active'); //remove the classes from all the menus
   $(this).addClass('active');
});

Even if not

$("#work").click(function () {
    $("#work, #about, #testimonial, #instruction, #blog, #contact").removeClass('active');
    $(this).addClass('active');
});
Read more
...

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