addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgooglegroupshelp-with-circleimageimagesinstagramFill 1linklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

Baltimore PHP Message Board › need help on some php classwork

need help on some php classwork

Jamar
user 63775032
Baltimore, MD
Post #: 1
a lot of my php code is wrong so I need someone to point me in the right direction.
Trevor G.
tgryffyn
Edgewater, MD
Post #: 5
Can you give examples of what you think is wrong and what it's doing/not doing that seems broken? Maybe a few tips will set you on the right path to fixing all of it.
Jamar
user 63775032
Baltimore, MD
Post #: 2
sorry for the late reply... had the flu, but anyways.... thanks
I suck at arrays and these are my instructions
1. create a form that takes ten names and email addresses
2. create a php program that uses a text file as a template to send out personalized party invitations to each email address

*the text template is altered in each email to include the name of the guest I'm inviting*
*no form validation is required*

my problem is:
1. $_POST["name"] is an array and I need to pick the correct element out of it and replace #NAME# with that. Should I use a foreach loop.... what is best

or

2. I can change my HTML and give each text input a different value for "name", such as name="name1", name="name2", etc...

this is what I have so far for my php code:

<?


function mail_message($data_array, $template_file){

$email_message = file_get_contents($template_file);
$email_message = str_replace("#NAME#", $_POST['name'], $email_message);


for($i=0; $i <= 10; $i++){

$to = $data_array['email'];
$from = "iwalkonwater2@aol.com";
$subject = "pajama party";

mail($to[$i], $subject, $email_message, "From: ".$from);
}
}


mail_message($_POST, $_SERVER['DOCUMENT_ROOT']."/party.t­xt");


echo "<h3>Thank You</h3>";

?>
Trevor G.
tgryffyn
Edgewater, MD
Post #: 6
Sorry man, busy weekend.. let's take a look...

Ok, so without changing a bunch of stuff and working with the assignment given, you're really close.

When you have an HTML form and use name="name[]" and name="email[]" for each entry, yes.. you end up with an array for each one. Arrays always contain pairs of data as a key and a value.

If you have a block of code like this:
$name[] = 'Bob';
$name[] = 'Fred';
$name[] = 'Bill';

... that's essentially what your HTML form is doing.

This takes $name (or in your form example, $_POST['name']) and adds a key/value pair each time you use [] with the key being a number and going in numeric order.

Since the array doesn't exist already before it's created in $_POST, then the keys start with 0 and go up from there.

So in my example, $name[0] would be 'Bob' and $name[1] would be 'Fred' and so on.

You can also used named keys, so you can do $name['first'] = 'Bob' then reference it again with $name['first']. And you can have numbers and strings as array keys within the same array.

But back to your problem. If your form inputs look like this:
<input type="text" name="name[]" /><input type="text" name="email[]" /><br />
<input type="text" name="name[]" /><input type="text" name="email[]" /><br />
<input type="text" name="name[]" /><input type="text" name="email[]" /><br />
etc...

...and assuming each name and email are grouped like that, then you can assume $_POST['name'][0] and $_POST['email'][0] go together.

So inside your for loop, you could have:
$to = $_POST['email'][$i];
$name = $_POST['name'][$i];

Your for statement is probably going to go over by one since the ten items will be numbered 0 through 9. So try changing it to:
for ($i = 0; $i < 10; $i++)

(I always have to double check my for statements, but pretty sure that'll go until it processes 9 then increments to 10 and stops looping because $i < 10 is false at that point)

Another note, your $email_message is going to get overwritten and #NAME# won't exist in it anymore after the first run. I'd do:
$template = file_get_contents($template_file);

Then inside the for loop do:
$email_message = str_replace('#NAME#', $_POST['name'][$i], $template);

Then you're keeping a clean copy of $template for later name replacements AND you're using the current $i value to get the name associated with the $i position in the array.

Finally, you can get rid of $data_array as a parameter for the function since $_POST is globally available (meaning you can remove $_POST from where you call mail_message() near the bottom as well)

...and you can change the mail($to[$i],.... to just mail($to, .... since if you made the change I mentioned above, $to is already the value of $_POST['email'][$i].

There's lots of other stuff you can do, but that's the basic answers to what you asked.

If you make changes and it still doesn't work, feel free to post the new code and I'll take another look. I may not have explained it very well.

Good luck!

-Trevor
Jamar
user 63775032
Baltimore, MD
Post #: 3
worked perfect.... and you gave me a better understanding of arrays, thanks

I have another one too, its a calendar I created I have some questions on... give me a few, I'll show you the code.
Jamar
user 63775032
Baltimore, MD
Post #: 4
I had to create a shopping cart with a username/ password login and without a database, using arrays for products. I know it sounds weird but I guess its to help me learn basic functions, which as you can see I'm having some trouble in. I have 3 files:

I tried to keep it as simple as possible, without css or any validations, since I wouldn't use this technique in any real life application.

The problem I'm having is this: I can't get my products to the shopping cart. Each item has an "additem" to cart button, but I must be overlooking something important and can't figure it out.



FILE 1.
<?php
//name this file "users.php"
//this method does not secure passwords
//"accounts", 2D array
$accounts = array (
array("username" => "username1", "password" => "root"),
array("username" => "username2", "password" => "root2"),
array("username" => "username3", "password" => "root3"),

);

?>



FILE 2.
<?php
//name this file "products.php"
$products = array (
array("itemid" => "1", "name" => "green tea", "price" => "14.99", "description" => "asian green tea"),
array("itemid" => "2", "name" => "mint tea", "price" => "14.99", "description" => "india mint tea"),
array("itemid" => "3", "name" => "lemon tea", "price" => "8.99", "description" => "cold and flu lemon tea"),
array("itemid" => "4", "name" => "earl grey", "price" => "8.99", "description" => "anytime earl gray tea"),
array("itemid" => "5", "name" => "jasmine tea", "price" => "12.99", "description" => "soothing jasmine tea")
);
?>



FILE 3.
name this file "index_learn.php"
<?
session_name();
session_start();

//debugging
$error = '';

//login and products!
include("users.php");
include("products.php");


//logging in
$action = (isset($_GET['action'])) ? $_GET['action']: ""; //Ternary operator asking if there is an inputted action


switch($action)
{
case "login":
if(isset($_SESSION['username'])) //check if we're already logged in
{
$error['Login'] = "We've already logged in!";
} else {
$error['login'] = "Invalid username/password";
$username = (isset($_POST['username'])) ? $_POST['username']: ""; //check if there is a username supplied, if not then leave it blank
$password = (isset($_POST['password'])) ? $_POST['password']: ""; //check for password
foreach($accounts as $value) //this is our login attempt
{
if(($username == $value['username']) && ($password == $value['password']))
{
//Quick login validation method
$_SESSION['username'] = $username;
$_SESSION['cart'] = ''; //this is our cart for the user this session
unset($error['login']);
}
}
}
break;
case "logout":
session_unset(); //deletes all session variables/cookies
break;
case "additem":
//this is a quick way to make a cart
$itemid = (isset($_GET['itemid'])) ? $_GET['itemid']: "";
if($itemid != "")
{
if($_SESSION['cart'] == "")
{
$_SESSION['cart'] = array($products[$itemid]); // add your product to shopping cart
} else {
array_push($_SESSION['cart'], $products[$itemid]); // adding more items to the shoping cart... stacking with push array
}
}
break;
case "clearcart":
$_SESSION['cart'] = ""; // clears cart
break;
}

//now check to see if we're logged in or not
if(isset($_SESSION['username'])) //now i'm using the true/false return of the "isset" function to determine if we've set (logged in) this variable
{
//we're logged in... so lets show some stuff!
$dUsername = $_SESSION['username'];

echo 'Welcome ' .$dUsername. '! Its nice to see you back! Click <a href="index_learn.php?action=logout­" id="logout">here</a> to logout!<br /><br />';
echo "Stuff we have in our cart:<br />\n";
$cart_total = 0;
if($_SESSION['cart'] != '') {
foreach($_SESSION['cart'] as $key => $value){
$cart_total = $cart_total + $value['price'];
$name = $value['name'];
$price = $value['price'];
$desc = $value['description'];
echo $name, $$price, $desc;

}
}
echo "Cart total: $".$cart_total;
echo '<br /><input type="submit" value="Clear Cart" id="clearcart"><br /><br />';



echo "Click an item to add it to your cart:<br /><br />";
foreach($products as $key => $value){
$id = $value['itemid'];
$name = $value['name'];
$price = $value['price'];
$desc = $value['description'];
echo $name." " .$price. " " .$desc;
echo '<input type="submit" value="Add" id="additem"><br /><br />';

}

}



else { //isset if
//no we're not logged in, show our login form
?>
<form method="post" action="index_learn.php?action=logi­n" id="login_form">
Username:<br />
<input type="text" placeholder="Username" name="username" id="login_username" /><br />
<br />
Password:<br />
<input type="password" placeholder="Password" name="password" id="login_password" /><br />
<br />
<input type="submit" value="Login" id="login_button" />
</form>
<?
}

?>
Trevor G.
tgryffyn
Edgewater, MD
Post #: 7
So it looks like you're trying to keep all the products bundled in a nice little array for each one, but when you use $products[$itemid] to reference a product, you're not getting it by product ID. You're asking PHP for an array key that's different from the actual item id.

You could try something like this:

foreach ($products as $product) {
if ($itemid == $product['itemid']) = array_push($_SESSION['cart'], $product);
// note $product here, it's the array within $products that you want

}


Another way to handle it is to use the itemid as the array key. Since the itemids should be unique, this shouldn't cause any issue with overwriting data.


$products[1] = array("name" => "green tea", "price" => "14.99", "description" => "asian green tea"),
$products[2] = array("name" => "mint tea", "price" => "14.99", "description" => "india mint tea"),
$products[3] = array("name" => "lemon tea", "price" => "8.99", "description" => "cold and flu lemon tea"),
$products[4] = array("name" => "earl grey", "price" => "8.99", "description" => "anytime earl gray tea"),
$products[5] = array("name" => "jasmine tea", "price" => "12.99", "description" => "soothing jasmine tea")


if (isset($products[$itemid])) {
array_push($_SESSION['cart'], $products[$itemid]);
} else {
// product not found
}



Also remember that...
array_push($_SESSION['cart'], $products[$itemid]);
... is the same as ...
$_SESSION['cart'][] = $products[$itemid];


Well, not completely the same. I think you can use array_push() with multiple items. But in this case, you're using it with a single item (that single item just happens to be an array with multiple items inside it, but it's essentially a single item in this case).

One thing about PHP is that there's usually a couple different ways to do things. People coming from other languages might be used to array_push() so PHP accomodates by allowing it, but there are shortcuts too.


Last note... just a random aside.. session_name() without parameters returns the current session name, so using it before session_start() does nothing. And you probably don't need it even if you gave it a name to use unless you had a specific need to name your session


See if that helps and if not, let me know what's stuck at this point. I didn't go over everything with a fine tooth comb, but that's at least one issue you might be having.
Jamar
user 63775032
Baltimore, MD
Post #: 5
Ok, I see your point about array key and the actual item id.

I tried the first way but I received a error in the code with the "=" sign of the if statement
= array_push($_SESSION['cart'], $product);


I like the way you used the itemid as the array key. If I do it this way should I just write $produts[]= into the index, and delete the include ("products.php"); ?



And this if statement would that go into my switch action of the case "additem"?

if (isset($products[$itemid])) {
array_push($_SESSION['cart'], $products[$itemid]);
} else {
// product not found
}


I have the feeling that I'm making a mistake with my submit button

echo $name." " .$price. " " .$desc. ' <input type="submit" value="Add Item" id="additem"><br />';
Powered by mvnForum

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy