foreach as key vaue otherwise null

I am trying to turn

$abc = (isset($_POST[“abc”]) ? $_POST[‘abc’] : null);
/* there are 15 more of these */

into a foreach as key => value otherwise null

Used on the top of a php_self form processor.

I understand:
foreach($_POST as $key => $value)

but I don’t know how to add the isset or default ‘null’ in there.

Thanks
Tom

What is the end result of what you are trying to accomplish? What are you doing with nulls? It is helpful to get an idea of the big picture to give you the best answers.

ah, I think I know what you want.

[php]$fields = array(‘abc’, ‘abc2’, ‘abc3’, ‘abc4’, ‘abc5’, ‘abc6’); // etc

$data = array();
foreach ($fields as $field) {
$data[$field] = !empty($_POST[$field]) ? $_POST[$field] : null;
}

echo ‘

’;
print_r($data);[/php]

Thanks for the reply

I have 15 or so of
$foo = (isset($_POST[“foo”]) ? $_POST[‘foo’] : null);
$bar = (isset($_POST[“bar”]) ? $_POST[‘bar’] : null);
$foobar = (isset($_POST[“foobar”]) ? $_POST[‘foobar’] : null);
as I process the form.

The “null” part is to keep from getting all kinds of undefined variable errors. (There are no values for foo bar and foobar until the form is posted to self)

The code works as is but I am quite sure that the same thing can be done with a foreach array. Processing the form with foreach($_POST as $key => $value) style but need to add in the default null

Every time I add an input field in the form,

I have to remember to create the corresponding
$foo = (isset($_POST[“foo”]) ? $_POST[‘foo’] : null); form processing line.

If I had a form with 300 input fields, currently I would need 300 corresponding processing lines, surely this can be done with a couple lines of foreach($_POST as $key => $value)

I don’t “need” the answer to this, I’m just wanting to improve my code.
Tom

@benanamen

I just copied your Password Hashing from post:
“Dropdown list - populated by a mysql db to search another mysql table”

How do you handle “forgot password” can you email their password to them or do you need to send an email with special link to create new password?

Tom

Post the whole thing of what you have done so we don’t have to guess at what is going on. There is definitely a better way than what you describe you have done.

No, you cannot email them a password because it is stored encrypted in the database. I email an AES encrypted link for them to reset their password. Even you dont know their passwords even looking directly at the database. You will want to set an expire time for the reset link for extra security. The AES encryypt/decrypt function is posted in the functions.php

The only way you could actually send them a password is if you generate it yourself and send it to them, but, sending a plain text password defeats your security.

If you are on newer PHP I would change the crypt to bcrypt. I may just update the post to “Force” people to be on newer PHP to use it.

I didnt post password/login files because the only reason I put the files up that I did is to get people immediately off old mysql_* and onto PDO with something they could understand fairly easy.

This is stripped down as much as possible and still have the code work. This form only has 6 input fields but that can grow to 20 or more.

This was my first attempt at constructing a prepared statement and basically the first time writing mysqli_*.

[code]<?php

/* Contains connection variables and $site */
include “con_and_site.php”;

/* retrieve subdomain = username */
$host = explode(’.’, $_SERVER[“HTTP_HOST”]);
if ($host[0] == ‘www’) array_shift($host);
//Remove the base domain. Assumes a one dot (example.com) domain
$host = array_slice($host, 0, -2);
$sub_d = implode(’.’, $host);

$pas = (isset($_GET[‘pas’]) ? $_GET[‘pas’] : null);
$list = (isset($_POST[“list”]) ? $_POST[‘list’] : null);
$fname = (isset($_POST[“fname”]) ? $_POST[‘fname’] : null);
$lname = (isset($_POST[“lname”]) ? $_POST[‘lname’] : null);
$user1 = (isset($_POST[“user1”]) ? $_POST[‘user1’] : null);
$user2 = (isset($_POST[“user2”]) ? $_POST[‘user2’] : null);
$user3 = (isset($_POST[“user3”]) ? $_POST[‘user3’] : null);
/* There are about 12 more of these. */
$save = (isset($_POST[“save”]) ? $_POST[‘save’] : null);
$i = (isset($_POST[“i”]) ? $_POST[‘i’] : null);

/* Pre-qualify update */
$update = “1”; // update = Yes
if($sub_d === “” || $pas === NULL){$update = “0”;} // Update = No

/* Defining variables */
$message = “Use this form to update your information.”;
$status_msg = “0”;
$pass = “?pas=$pas”;

if($update === “1”) { // bypassed if update reset to 0

/* ** Procedural style prepared statements ** */

$link = mysqli_connect("$fee", “$fie”, “$foe”, “$fum”);

if (mysqli_connect_errno()) {
printf(“Connect failed: %s\n”, mysqli_connect_error());
exit();
}

if($save !==“1”) {

// find user - match user1 and user2 to variables $sub_d and $pas

$query = “SELECT fname,lname,user1,user2,user3 FROM lm_users
WHERE user1 = ? AND user2 = ?”;

$stmt = mysqli_prepare($link, $query);

mysqli_stmt_bind_param($stmt, ‘ss’, $sub_d, $pas );

/* execute statement */
mysqli_stmt_execute($stmt);

/* store result */
mysqli_stmt_store_result($stmt);

if (mysqli_stmt_num_rows($stmt) < “1”){ $update = “0”; }

/* bind result variables */
mysqli_stmt_bind_result($stmt, $fname, $lname, $user1, $user2, $user3);

/* fetch values */
while (mysqli_stmt_fetch($stmt)) {$fname; $lname; $user1; $user2; $user3;}

/* close statement */
mysqli_stmt_close($stmt);

            } // closing - if save !==1

                 }   // closing - if update=1 

if($update === “1”) { // bypassed if $update is now “0”

// SAVE

if($save === “1”) {

$query2 = “UPDATE lm_users SET fname = ?, lname = ?, user3 = ?
WHERE user1 = ? AND user2 = ?”;

$stmt2 = mysqli_prepare($link, $query2);

mysqli_stmt_bind_param($stmt2, ‘sssss’, $fname, $lname, $user3, $sub_d, $pas);

mysqli_stmt_execute($stmt2);

mysqli_stmt_close($stmt2);

/* Retrieve updated content and populate form */
$row = “SELECT fname,lname,user1,user2,user3 FROM lm_users
WHERE user1 = ? AND user2 = ?”;

$stmt3 = mysqli_prepare($link, $row);

mysqli_stmt_bind_param($stmt3, ‘ss’, $sub_d, $pas);

mysqli_stmt_execute($stmt3);

/* likely do not need this */
mysqli_stmt_store_result($stmt3);
if (mysqli_stmt_num_rows($stmt3) < “1”){ exit;}

/* bind result variables */
mysqli_stmt_bind_result($stmt3, $fname, $lname, $user1, $user2, $user3);

/* fetch values */
while (mysqli_stmt_fetch($stmt3)) {$fname; $lname; $user1; $user2; $user3;}

/* close statement */
mysqli_stmt_close($stmt3);

/* activate message */
$status_msg = “1”;

/* close connection */
mysqli_close($link);

if($status_msg !== “0”) {

             $a = $i + 1; 
             $i = $a;

            if($i %2 == 0)
    {
        $message = "Your Information has been saved again!";
        }
    else
    {           
                    $message = "Your Information has been saved!";
    }

}

} //closing if save=1

$sub_d = htmlspecialchars($sub_d);
$pas = htmlspecialchars($pas);
$fname = htmlspecialchars($fname);
$lname = htmlspecialchars($lname);
$user1 = htmlspecialchars($user1);
$user2 = htmlspecialchars($user2);
$user3 = htmlspecialchars($user3);

echo "

First Name: <input name=“fname” size=“45” type=“text” value="$fname">



Last Name: <input name=“lname” size=“45” type=“text” value="$lname">


<textarea name=“user3” style=“height: 200px”> $user3



<input value=“Submit Changes” type=“submit”> $message $i

"; exit(); } // closing 2nd if update=1

?>
You must use your personal URL with password to update your information.
[/code]

Lets forget your code for a second, What is it that you are wanting to do?

Also. post your database schema with a few sample records.

Look up user based on subdomain
populate form with current data
on submit of form
post form back to self
update MySQL
retrieve updated data
populate form with updated data.

[code] row - lm_users

Column

1 id
2 uid
3 list
4 fname
5 lname
6 email
7 user1
8 user2
9 user3
10 user4
11 user5
12 user6
13 user7
14 user8
15 user9
16 user10
17 user11
18 user12
19 user13
20 user14
21 user15
22 user16
23 user17
24 user18
25 user19
26 user20
27 cseq
28 cdel
29 cnf
30 dateadd
31 ipaddr
32 refurl
33 htmail
34 bounces

There are 20 custom users fields named user1 through user20 [/code]

Ok, got the explanation now. Simple enough.

I mean the sql to recreate your tables. I am seeing problems with your database design

It would look like this:
[php]SET FOREIGN_KEY_CHECKS=0;


– Table structure for publishers


DROP TABLE IF EXISTS publishers;
CREATE TABLE publishers (
publisher_id int(11) NOT NULL AUTO_INCREMENT,
publisher_name varchar(255) NOT NULL,
PRIMARY KEY (publisher_id,publisher_name),
KEY publisher_id (publisher_id)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


– Records of publishers


INSERT INTO publishers VALUES (‘1’, ‘DC’);
INSERT INTO publishers VALUES (‘2’, ‘Marvel’);
INSERT INTO publishers VALUES (‘3’, ‘Dark Horse’);
INSERT INTO publishers VALUES (‘4’, 'Dark Horse Manga ');
INSERT INTO publishers VALUES (‘5’, ‘Disney Comics’);
INSERT INTO publishers VALUES (‘6’, ‘Dragon Lady Press’);


– Table structure for search


DROP TABLE IF EXISTS search;
CREATE TABLE search (
search_id int(11) NOT NULL AUTO_INCREMENT,
publisher_id int(11) DEFAULT NULL,
title varchar(250) NOT NULL,
description varchar(250) NOT NULL,
keywords text NOT NULL,
link varchar(250) NOT NULL,
PRIMARY KEY (search_id),
KEY publisher_id (publisher_id),
CONSTRAINT search_ibfk_1 FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


– Records of search


INSERT INTO search VALUES (‘1’, ‘3’, ‘Blackhawks52’, ‘Blackhawks New 52 2011’, ‘blackhawks,new,52,2011,blackhawks52,blackhawks2011,black,hawks,dc,detective comics,’, ‘search/publisherid/dc/b/blackhawks/blackhawksnew52/blackhawks52.html’);
INSERT INTO search VALUES (‘2’, ‘2’, 'Mass Effect: Redemption ', '2010 Mini-Series ', ‘dark horse,dark,horse,mass effect,mass effect redemption, 2010,mini series’, ‘search/publisherid/darkhorse/m/masseffectredem/masseffectredem.html’);
INSERT INTO search VALUES (‘3’, ‘2’, ‘Women Of Marvel’, ‘Marvel 2011’, ‘marvel,women,of,2011,’, ‘search/publisherid/marvel/w/wom/wom.html’);
INSERT INTO search VALUES (‘4’, ‘3’, ‘Xena Warrior Princess’, ‘Xena warrior princess’, ‘dark horse,xena,princess,warrior,gabrielle’, ‘search/publisherid/darkhorse/x/xena/xwp/xwp.html’);[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service