Solved

Create variables in a foreach loop

Posted on 2014-03-25
20
253 Views
Last Modified: 2014-03-25
Hi,

i have a foreach loop containing names of columns which are the exact same of variables found within a form i have created. The form is dynamically created via the names of the columns in an sql table. i am curious if it is possible is possible to do something like so

$array="id, name, status, content, author";
foreach($array as $item){
   
   $new_array[]="(:".$item.") =>".$item;

}

Open in new window


where the first array item $new_array[0]  would be (:id)=>$id where the $id is the actual id variable created by the form

thanks in advance
0
Comment
Question by:M. Jayme Nagy
  • 7
  • 6
  • 4
  • +1
20 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39953589
If you want to create an array from a string then just do

$array="id, name, status, content, author";
$new_array=explode(", ",$array);

Open in new window

Anything other than that then I have no idea what you are trying to do.

Kinda looks like you are trying to build up a PDO array for execution...
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39953597
If you just want each item of the new array be a string formatted 'as' array key-value your code is right.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39953611
Kinda looks like you are trying to build up a PDO array for execution...
Great guess!
So you just build an array and pass it to PDO

$array="id, name, status, content, author";
foreach($array as $item){
   
   $new_array["(:".$item.")"]= $item;

}
$sth->execute($new_array);

Open in new window

0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39953618
Thats exactly what i am trying to accomplish

i am trying to create it dynamically so i do not need to make a separate one for each form i have.


sorry $array is an actual array not a string.
so it would look more like

array{
  [0] =>id
  [1].....
}
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39953626
If you are indeed building an array for PDO, and you form inputs EXACTLY match your table columns, then you don't need to build an array - you already have one - $_POST!

Just pass that into your query.

If you're building an array for some other reason, then we'll need more info. Firstly, you'll need to split out your string as Gary has pointed out. Then you'll need to tell us where you're planning on get the value of $id from.
0
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 500 total points
ID: 39953627
Or maybe:
$array="id, name, status, content, author";
foreach($array as $item){
   
   $new_array["(:".$item.")"]= $$item;

}
$sth->execute($new_array);

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
ID: 39953648
And where are the values coming from? All that will do is set the array index name and the value to the same thing...which kinda doesn't make sense.

(Chris already asked this)
0
 
LVL 58

Expert Comment

by:Gary
ID: 39953683
Is it posted values? Something like this maybe.

$pdo= array();
foreach($column_array as $col){
	$pdo=array_merge($pdo,array(":".$col=>$_GET[$col]));
}

$stmt->execute($pdo);

Open in new window


edit
I guess Marco's comment is doing basically the same thing.
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39953716
Why, why, why do people insist on creating problems where there are none?

If your data is being sent from a form and that data already matches your database table, why go to all the trouble of creating another array?
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39953732
because i create separate variables from the post array and format / test them independently. as well as some perform different tasks. so the $_POST array is not EXACTLY the same

the original array puts everything back together so i can use it they way i want
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39953755
OK, but if you want to pass your array into a PDO prepared statement, this won't work:

$new_array["(:".$item.")"]= $$item;
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39953785
I would agree with Chris, but I have two little doubts: first, one has anyway to filter $_POST array from submit. Secondly, that POST array leys have to be edited to add the prefix colon for prepared statements.
This second problem is eaily solvable changing the names of your form fields: add there the prefix and you'll get the $_POST array almost ready.

For the first problem, simply use array_pop() to delete the last value of the $_POST array, the submit value.

Try this code to see how it works:
<?php
if (isset($_POST['submit']))
{
	array_pop($_POST);
	echo "<pre>";
	var_dump($_POST);
	echo "</pre>";
}
?>
<form action="" method="post">
	<input type="text" name=":id" value="1" />
	<input type="text" name=":name" value="your_name" />
	<input type="text" name=":status" value="your_status" />
	<input type="text" name=":content" value="your_content" />
	<input type="text" name=":author" value="your_author" />
	<input type="submit" name="submit" value="Submit" />
</form>

Open in new window


At this point, you pas $_POST array to pdo->execute() instead of dumping it.

And now, I think you have to request attention and at least split points between all experts :)

Cheers
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39953801
Firstly, just don't give your Submit button a 'name' attribute and it won't get passed in the $_POST array.

Secondly, the array to pass into PDO doesn't have to have the colon prefix - that's just for the placeholders themselves.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39953810
Clean and simple! :) Let me ask just a thing: I didn't test my code, but why wouldn't it work?

I mean $new_array["(:".$item.")"]= $$item;
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39953841
$new_array["(:".$item.")"]= $$item;

should be

 $new_array[":".$item.""]= $$item;

that was my mistake
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39953849
Your array would look like this:

array(
   (:var1) => value1,
   (:var2) => value2
);


That won't work with PDO because of the brackets. You need something like this:

array(
   var1 => value1,
   var2 => value2
)


and although you don't 'need' the colon prefix, it will still work like this:

array(
   :var1 => value1,
   :var2 => value2
)
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39953885
Thanks, Chris.

@M. Jayme Nagy: as you see, that was a my mistake too. Even not using $_POST array, I should have seen those stupid brakets and I should have deleted them! Anyway, I think you can consider to split points.

Cheers
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39953913
not sure if i can go back but if you would like it that way then im fine with it
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39953940
I'm not worried about the points.

I just wanted it shown that the answer accepted was not correct, nor best-practice. This was more for the benefit of future-readers than yourself.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39954119
To split points simply request attention using the link below the question box and ask the moderator to reopen question, then assign points as needed.

Thank you
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
php simple error message 4 23
ignore other .htaccess 2 45
Curl & PHP Command Help 4 23
Creating Functions in phpMyAdmin 8 17
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question