12 Replies - 382 Views - Last Post: 17 November 2013 - 04:26 AM Rate Topic: ***** 1 Votes

#1 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

variables in variables

Posted 09 November 2013 - 08:00 AM

I am currently creating a system in which I can create and disable site links.However, the way in which I have programmed it requires me to go back and edit the programming every time I try to create/modify new links.To alleviate this problem, (I don't really think this is possible), but I was wondering this:

Is is possible to have a variable within a variable in php?

For example, something like this?

$option_NEW OPTION VARIABLE = (isset($_POST['option_NEW OPTION VARIABLE'])) ? htmlentities($_POST['option_NEW OPTION VARIABLE']) : '' ;

Is This A Good Question/Topic? 0
  • +

Replies To: variables in variables

#2 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Re: variables in variables

Posted 09 November 2013 - 08:21 AM

I haven't tested this but I believe you can just do:

$_POST[$someVariable]

IIRC you can omit the apostrophes.

Do you need to do it this way though? You could instead loop through the $_POST array reading the key-names, or even just extract the key-names into another array. But it, of course, depends what you are trying to achieve.

This post has been edited by andrewsw: 09 November 2013 - 08:24 AM

Was This Post Helpful? 0
  • +
  • -

#3 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

Re: variables in variables

Posted 09 November 2013 - 08:30 AM

Here is a better example:

			<?php
				$sites = "SELECT site,name,active FROM `sites`";
$ps = $pdo_2->query($sites);
while ($row = $ps->fetch(PDO::FETCH_ASSOC)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="<?php echo $row['name']; ?>">
<h1><b><a href="<?php echo $row['site']; ?>"><?php echo $row['name']; ?></a></b></h1><br />
<input type="radio" name="option_<?php echo $row['name']; ?>" value="yes" <?php if ($row['active'] == 'yes') echo ' checked="checked"' ?> />Site Undisabled&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="option_<?php echo $row['name']; ?>" value="not_active" <?php if ($row['active'] == 'not_active') echo ' checked="checked"' ?>>Site Disabled<br>
<br>
<input type="text" value="<?php echo $row['site']; ?>" name="link_<?php echo $row['name']; ?>" size="40" /><br /><br />
<input type="submit" value="Update '<?php echo $row['name']; ?>'" name="<?php echo $row['name']; ?>_submit" />
<hr size='1'/></td></tr><tr><th align='left'>
<br><br>
</form>
<?php
if (isset($_POST[''.$row['name'].'_submit']))
{
date_default_timezone_set('GMT'); 
date_default_timezone_set("Europe/London");
$date = date('d/m/Y');

$site = $row['name'];
$option = (isset($_POST['option_'.$row['name'].''])) ? htmlentities($_POST['option_'.$row['name'].'']) : '' ;
$link = (isset($_POST['link_'.$row['name'].''])) ? htmlentities($_POST['link_'.$row['name'].'']) : '' ;

$sql = "UPDATE `sites` SET active = :active, last_changed, site = :link = :date WHERE name = :site"; 	 
$ps = $pdo_2->prepare($sql);  
$ps->execute(array(
':active'=>$option,
':date'=>$date,
':link'=>$link,
':site'=>$site));  
?>
<META http-equiv="refresh" content="0;URL=redirect.php?redirect=http://www.strongholdnation.co.uk/admin/site_options.php">
<?php } } ?>




No I accidently looked on the wrong page, it didn't work.Once I press the submit button, nothing happens.Here is the code I am using:

<?php
				$sites = "SELECT site,name,active FROM `sites`";
$ps = $pdo_2->query($sites);
while ($row = $ps->fetch(PDO::FETCH_ASSOC)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="<?php echo $row['name']; ?>_form">
<h1><b><a href="<?php echo $row['site']; ?>"><?php echo $row['name']; ?></a></b></h1><br />
<input type="radio" name="option_<?php echo $row['name']; ?>" value="yes" <?php if ($row['active'] == 'yes') echo ' checked="checked"' ?> />Site Undisabled&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="option_<?php echo $row['name']; ?>" value="not_active" <?php if ($row['active'] == 'not_active') echo ' checked="checked"' ?>>Site Disabled<br>
<br>
<input type="text" value="<?php echo $row['site']; ?>" name="link_<?php echo $row['name']; ?>" size="40" /><br /><br />
<input type="submit" value="Update '<?php echo $row['name']; ?>'" name="<?php echo $row['name']; ?>" />
<hr size='1'/></td></tr><tr><th align='left'>
<br><br>
</form>
<?php
$sitename = $row['name'];
if (isset($_POST[$sitename]))
{
date_default_timezone_set('GMT'); 
date_default_timezone_set("Europe/London");
$date = date('d/m/Y');

$site = $row['name'];
$option = (isset($_POST['option_'.$row['name'].''])) ? htmlentities($_POST['option_'.$row['name'].'']) : '' ;
$link = (isset($_POST['link_'.$row['name'].''])) ? htmlentities($_POST['link_'.$row['name'].'']) : '' ;

$sql = "UPDATE `sites` SET active = :active, last_changed, site = :link = :date WHERE name = :site"; 	 
$ps = $pdo_2->prepare($sql);  
$ps->execute(array(
':active'=>$option,
':date'=>$date,
':link'=>$link,
':site'=>$site));  
?>
<META http-equiv="refresh" content="0;URL=redirect.php?redirect=http://www.strongholdnation.co.uk/admin/site_options.php">
<?php } } ?>


This post has been edited by chris98: 09 November 2013 - 08:28 AM

Was This Post Helpful? 0
  • +
  • -

#4 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

Re: variables in variables

Posted 16 November 2013 - 05:44 AM

I have changes it to this, but it still isn't working. Would you be able to point me in the right direction as to what I've done wrong?

			<?php
				$sites = "SELECT site,name,active FROM `sites`";
$ps = $pdo_2->query($sites);
while ($row = $ps->fetch(PDO::FETCH_ASSOC)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="<?php echo $row['name']; ?>_form">
<h1><b><a href="<?php echo $row['site']; ?>"><?php echo $row['name']; ?></a></b></h1><br />
<input type="hidden" name="sitename_<?php echo $row['name']; ?>" />
<input type="radio" name="option_<?php echo $row['name']; ?>" value="yes" <?php if ($row['active'] == 'yes') echo ' checked="checked"' ?> />Site Undisabled&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="option_<?php echo $row['name']; ?>" value="not_active" <?php if ($row['active'] == 'not_active') echo ' checked="checked"' ?>>Site Disabled<br>
<br>
<input type="text" value="<?php echo $row['site']; ?>" name="link_<?php echo $row['name']; ?>" size="40" /><br /><br />
<input type="submit" value="Update '<?php echo $row['name']; ?>'" name="<?php echo $row['name']; ?>" />
<hr size='1'/></td></tr><tr><th align='left'>
<br><br>
</form>
<?php
$sitename = (isset($_POST['sitename_'.$row['name'].''])) ? htmlentities($_POST['sitename_'.$row['name'].'']) : '' ;
if (isset($_POST[$sitename]))
{
date_default_timezone_set('GMT'); 
date_default_timezone_set("Europe/London");
$date = date('d/m/Y');

$site = (isset($_POST['sitename_'.$row['name'].''])) ? htmlentities($_POST['sitename_'.$row['name'].'']) : '' ;
$option = (isset($_POST['option_'.$row['name'].''])) ? htmlentities($_POST['option_'.$row['name'].'']) : '' ;
$link = (isset($_POST['link_'.$row['name'].''])) ? htmlentities($_POST['link_'.$row['name'].'']) : '' ;

$sql = "UPDATE `sites` SET active = :active, last_changed, site = :link = :date WHERE name = :site"; 	 
$ps = $pdo_2->prepare($sql);  
$ps->execute(array(
':active'=>$option,
':date'=>$date,
':link'=>$link,
':site'=>$site));  
?>
<META http-equiv="refresh" content="0;URL=redirect.php?redirect=http://www.strongholdnation.co.uk/admin/site_options2.php">
<?php } } ?>
<hr size='1'/></td></tr><tr><th align='left'> 


This post has been edited by chris98: 16 November 2013 - 05:45 AM

Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Re: variables in variables

Posted 16 November 2013 - 06:01 AM

You will need to explain the problem you are having, particularly as your code is hard to read.

  • It is not clear where your second while-loop ends.
  • The default time-zone should be set once, at the beginning of the code (not within a loop).
  • Meta-tags belong at the top of the page, in the head-tag.


Code Separation tutorial
Was This Post Helpful? 0
  • +
  • -

#6 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

Re: variables in variables

Posted 16 November 2013 - 06:28 AM

I am trying to cram all the disabling into one code, as I don't wish to have to go back into the file & edit it every single time I create a new site link.

But, Like I said above, I don't exactly know how as I think it would require a submit button variable. However, once I try to update the sites, nothing happens.It was supposed to update it the same way it did when I placed named submit buttons and forms, and then redirect the page to redirect.php, but as soon as I press the submit button, NOTHING happens at all - it's as if I didn't even press it.

I will change the default timezone, as I didn't know.

The reason I have the <meta> where it is is because once it submits and completes the action I wanted it to redirect.
Was This Post Helpful? 0
  • +
  • -

#7 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

Re: variables in variables

Posted 16 November 2013 - 06:54 AM

Do you know what I could do to fix it?

I'm pretty sure it has something to do with this bit:

$sitename = (isset($_POST['sitename_'.$row['name'].''])) ? htmlentities($_POST['sitename_'.$row['name'].'']) : '' ;
if (isset($_POST[$sitename]))
{



Or this bit:

$site = (isset($_POST['sitename_'.$row['name'].''])) ? htmlentities($_POST['sitename_'.$row['name'].'']) : '' ;
$option = (isset($_POST['option_'.$row['name'].''])) ? htmlentities($_POST['option_'.$row['name'].'']) : '' ;
$link = (isset($_POST['link_'.$row['name'].''])) ? htmlentities($_POST['link_'.$row['name'].'']) : '' ;

$sql = "UPDATE `sites` SET active = :active, last_changed, site = :link = :date WHERE name = :site"; 	 
$ps = $pdo_2->prepare($sql);  
$ps->execute(array(
':active'=>$option,
':date'=>$date,
':link'=>$link,
':site'=>$site));  


This post has been edited by chris98: 16 November 2013 - 06:55 AM

Was This Post Helpful? 0
  • +
  • -

#8 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Re: variables in variables

Posted 16 November 2013 - 07:23 AM

This is wrong:
$sql = "UPDATE `sites` SET active = :active, last_changed, site = :link = :date WHERE name = :site"; 

You aren't setting last_changed to anything and the double-assignment I wouldn't expect to work in an UPDATE statement.

Use echo-statements or, preferably, print_r() to check the values of your variables at various points.

Add the following to the top of your php so that you can see all errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');

This post has been edited by andrewsw: 16 November 2013 - 07:33 AM

Was This Post Helpful? 0
  • +
  • -

#9 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Re: variables in variables

Posted 16 November 2013 - 07:29 AM

Quote

The reason I have the <meta> where it is is because once it submits and completes the action I wanted it to redirect.

The meta-tag should be in the head-tag. If you want to redirect after the php has been processed then don't produce any html output and use the header() function to relocate. The tutorial I linked to about code-separation will help you to only produce html-output if you are not going to redirect.
Was This Post Helpful? 0
  • +
  • -

#10 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

Re: variables in variables

Posted 17 November 2013 - 03:39 AM

To be honest, I don't even know what possessed me to even think about using a <meta> tag in the first place.Header() is much better, and I normally use that.I obviously must not have been thinking straight when I programmed it.

I also didn't notice the update error. However, that does prove that the action must never have triggered, as I would have recieved an SQL error.

I have put error reporting on, and I have not recieved any errors.I have also used print_r () and nothing has happened at all. So it must be a trigger action, as the header() doesn't trigger either.

It must be the:

if (isset($_POST[$sitename]))


that is to blame.
Was This Post Helpful? 0
  • +
  • -

#11 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3637
  • View blog
  • Posts: 5,765
  • Joined: 08-June 10

Re: variables in variables

Posted 17 November 2013 - 03:52 AM

I think you are making things unnecessarily complicated. Whatever happens; whatever site is being modified, you will only ever be modifying on site at a time. Therefore it isn't necessary to name all the inputs like that, and then query everything and check the form fields against the site names.

My suggestion would be this: Create your forms in a loop, like you do now, but instead of naming them all like: field_sitename, name them more simply, and add a hidden field to pass on the site name. Then you may as well post it to another form, to keep the code simple. For instance, make your forms look like this:
<form action="process_site_edit.php" method="post">
    <input type="hidden" name="site_name" value="site1">
    <input type="option" name="disabled" value="false"> Site Enabled<br>
    <input type="option" name="disabled" value="true"> Site Disabled<br>
    <input type="text" name="link" value="http://example.com/site/1">
    <input type="submit" value="Edit Site1">
</form>
<form action="process_site_edit.php" method="post">
    <input type="hidden" name="site_name" value="site2">
    <input type="option" name="disabled" value="false"> Site Enabled<br>
    <input type="option" name="disabled" value="true"> Site Disabled<br>
    <input type="text" name="link" value="http://example.com/site/2">
    <input type="submit" value="Edit Site2">
</form>



Now there is no need to be going through the sites again looking for matching POST elements. You can just process it normally:
<?php
if (isset($_POST["site_name"], $_POST["disabled"], $_POST["link"])) {
    $sql = "UPDATE sites SET 
                disabled = :disabled,
                link = :link
            WHERE name = :name";
    // And the bind, execute and do a header("Location...")
    // to send the user back, or whever he should be sent.
}
else {
    echo "<h1>Missing form input!</h1>";
    echo "<a href='javascript: history.back();'>Go Back</a>";
}




If you, however, do find yourself in a position where you need to send multiple values for the same field, PHP does treat array names that use array syntax as actual arrays when processing them. So this form:
<form action="process.php" method="post">
    <input type="text" name="siteLink[site1]" value="http://example.com/site/1">
    <input type="text" name="siteLink[site2]" value="http://example.com/site/2">
    <input type="text" name="siteLink[site2]" value="http://example.com/site/3">
</form>


When submitted, the POST array would look much like this in the receiving PHP script:
$_POST = [
    "siteLink" => [
        "site1" => "http://example.com/site/1",
        "site2" => "http://example.com/site/2",
        "site3" => "http://example.com/site/3"
    ]
];


So, you can see how that would be easier to deal with than your string concat version? Array functions could be used to make working with this simpler. For instance:
<?php
if (isset($_POST["siteLink"]) && is_array($_POST["siteLink"]) {
    foreach ($_POST["siteLink"] as $siteName => $linkURL) {
        $sql = "UPDATE sites SET link = :link WHERE name = :name";
        // Bind, execute, etc...
    }
}


Was This Post Helpful? 1
  • +
  • -

#12 chris98  Icon User is offline

  • D.I.C Addict

Reputation: 3
  • View blog
  • Posts: 567
  • Joined: 06-July 13

Re: variables in variables

Posted 17 November 2013 - 04:16 AM

Ah, I didn't think of that. Thanks, it works perfectly now!

I do have one question though. What is actually better?
Having a set file for your data to be managed with like the process_edit_form.php, or having a $_SERVER['PHP_SELF'] action?
Was This Post Helpful? 0
  • +
  • -

#13 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3637
  • View blog
  • Posts: 5,765
  • Joined: 08-June 10

Re: variables in variables

Posted 17 November 2013 - 04:26 AM

Depends on what you are doing. If the form submission produces validation errors, for instance, then it can be beneficial to use a self referencing form. A simple example of such a thing:
<?php
$validationerrors = [];
if (isset($_POST["title"], $_POST["message"])) {
    if (strlen($_POST["title"]) < 3) {
        $validationerrors["title"] = "Titles must be 3 or more letters.";
    }
    if (strlen($_POST["message"]) < 10) {
        $validationerrors["message"] = "Messages must be 10 or more letters.";
    }
    
    if (empty($validationerrors)) {
        // Process the stuff and header("Location: ...") away if needed.
    }
}
?>
<form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
    <input type="text" name="title" value="<?= getTitleValue(); ?>"><br>
    <?php if(isset($validationerrors["title"])): ?>
    <span class="error"><?= $validationerrors["title"] ?></span>
    <?php endif; ?>
    
    <textarea name="message"><?= getMessageValue() ?></textarea>
    <?php if(isset($validationerrors["message"])): ?>
    <span class="error"><?= $validationerrors["message"] ?></span>
    <?php endif; ?>
    
    <input type="submit">
</form>



Of course, if you are using a decent framework, such concerns aren't really a factor, since you'd be using templates. But for simpler code it can be beneficial.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1