Page 1 of 1

Variable variables!

Posted: Wed Jan 13, 2010 9:58 am
by spacebiscuit
This is driving me crazy:

while( isset($id{${z}}) ){
do something;
$z++;
}

So whilist $id1, $id2 etc. is set do something.

What am I doing wrong - thanks,

Rob.

Re: Variable variables!

Posted: Wed Jan 13, 2010 10:31 am
by spacebiscuit
Ok I think I have figured it out:

while( isset(${"{id}_${z}"}) ){

However, if I want to check for the $_POST variable (I have highlighted the code chages from the above snippet:

while( isset($_POST[{"{id}_${z}"}]) ){

And guess what? It does not work.

I'm lost!

Re: Variable variables!

Posted: Wed Jan 13, 2010 10:40 am
by AbraCadaver
There's probably a better way to do this using arrays in your form, but to answer your question:

Code: Select all

while(isset($_POST["{$id}_{$z}"])) {
    //
}

Re: Variable variables!

Posted: Wed Jan 13, 2010 10:52 am
by snipered
I agree, this is not a good way.

Pass an array to your function and skim through that.
Then you can do this.

Code: Select all

$passedValue = $_POST['arrayPassed'];
 
for ( $i = 0; i < size_of( $passedValue ); $i++ )
{
//do something
}

Re: Variable variables!

Posted: Wed Jan 13, 2010 11:06 am
by AbraCadaver
Not what I meant. Use arrays in the HTML form:

Code: Select all

<input type="text" name="something[]">
 
<!-- or -->
 
<input type="text" name="something[whatever][]">
Then you can loop through the $_POST array or the $something array. I would use foreach().

Re: Variable variables!

Posted: Wed Jan 13, 2010 2:18 pm
by spacebiscuit
Thanks guys, that has done the trick.

Now I stumped by this:

$query="UPDATE $_POST[table] SET title=$_POST[\"title\"] WHERE id=$_POST[id1]";

The quotatins surrounding 'title' are causing the page to not load which make n sense to me.

Rob.

Re: Variable variables!

Posted: Wed Jan 13, 2010 2:21 pm
by Benwahballz
Not sure if it will help or not but try this

Code: Select all

 
$query="UPDATE " . $_POST['table'] . " SET title= '" . $_POST['title'] . "' WHERE id= " . $_POST['id1'];
 
Try that and let me know

Re: Variable variables!

Posted: Wed Jan 13, 2010 2:27 pm
by AbraCadaver
You need to quote text in a SQL query. Also, this is very insecure and opens you up to SQL injection attacks. Try:

Code: Select all

$query = "UPDATE `" . mysql_real_escape_string($_POST['table']) . "` SET `title` = '" . mysql_real_escape_string($_POST['title']) . "' WHERE `id` = " . (int)$_POST['id1'];
-or-

Code: Select all

$table = mysql_real_escape_string($_POST['table']);
$title = mysql_real_escape_string($_POST['title']);
$id1 = (int)$_POST['id1'];
 
$query = "UPDATE `$table` SET `title` = '$title' WHERE `id` = $id1";

Re: Variable variables!

Posted: Wed Jan 13, 2010 2:59 pm
by spacebiscuit
Thanks that did the trick guys.

I'm having a bad day today and I'm unable to think straight.

Thanks for your help!

Rob.