Solved

Create variables in a foreach loop

Posted on 2014-03-25
20
256 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Help with mod_substitute 18 45
migrating to phpbb forum from vBulletin 4.2 3 42
Showing multiple maps using PHP and Google Maps 12 42
PHP: Filling Out/Creating a PDF 29 111
Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
This article discusses how to implement server side field validation and display customized error messages to the client.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to dynamically set the form action using jQuery.

730 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