/    Sign up×
Community /Pin to ProfileBookmark

I have strayed slightly from my studies and attempted to write my own little upload form script.

I am stuck on, well, a lot of places… But the one thing I am looking for is, if $variable = $_POST[‘variable’]; is empty, I would like another value uploaded to the database in it’s place.

Something like:

[code=php]
require_once(‘php/conn.php’);

if(isset($_POST[‘submit’]))
{
$day = $_POST[‘day’];
$month = $_POST[‘month’];
$year = $_POST[‘year’];
$title = $_POST[‘title’];
$sender = $_POST[‘sender’];
$picture = $_FILES[‘picture’][‘name’];
$output_form = false;

if(empty($day))
{ $day == date(‘j’); }
else { $day = $_POST[‘day’]; }

if(empty($month))
{ $month == date(‘F’); }
else { $month = $_POST[‘month’]; }

if(empty($year))
{ $year == date(‘Y’); }
else { $year = $_POST[‘year’]; }

if(empty($title))
{ $title == “no title”; }
else { $title = $_POST[‘title’]; }

if(empty($sender))
{ $title == “anonymous”; }
else { $title = $_POST[‘sender’]; }

if() {}

$connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(‘Problem connecting to Database’) ;
mysqli_select_db($connect, DB_NAME);

$query = “INSERT INTO images VALUES (0, ‘$day’, ‘$month’, ‘$year’, ‘$title’, ‘$sender’, ‘$picture’)” ;
$data = mysqli_query($connect, $query) or die(‘Problem Inserting into Database’);

echo ‘<h3>Image successfull uploaded</h3>’;
echo ‘Click here to insert another <a href=”manual.php”>Manual Upload</a>’;
mysqli_close($connect);
}

[/code]

to post a comment
PHP

41 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiDec 06.2009 — So what's the problem you are having?

Your current code is quite error prone, for example you will generate a notice level error if one of the fields you expect isn't set as you never check before trying to use it. There is also no need for all the re-assignment of variables, I still don't get why people always seem to think this is necessary!

[code=php]$_POST['foo'] = isset($_POST['foo']) && !empty($_POST['foo'] ? $_POST['foo'] : "default value";[/code]

BTW your current code is very insecure, I would have a read up on SQL injection attacks.
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 06.2009 — So what's the problem you are having?

Your current code is quite error prone, for example you will generate a notice level error if one of the fields you expect isn't set as you never check before trying to use it. There is also no need for all the re-assignment of variables, I still don't get why people always seem to think this is necessary!

[code=php]$_POST['foo'] = isset($_POST['foo']) && !empty($_POST['foo'] ? $_POST['foo'] : "default value";[/code]

BTW your current code is very insecure, I would have a read up on SQL injection attacks.[/QUOTE]


Yeah, I have read up some on SQL injections with trim() and so on...

I actuall have no clue what you wrote there, it doesn't make sense to me.

What I have is a Form. I enter the date ie: day, month, year, manually... If I leave those blank, and hit the submit button, I want the value that is uploaded to the database to be the the current dates (day, month etc) But if I fill in the values, I want those to be uploaded to the database.

Ie: 5 May 1979... Filled in. 6 December 2009... not filled in.

By reassigning variables I assume you are refering to this?

[code=php]
if(!empty($day)) { $_POST['day']; }
else { $day == date(''); }[/code]
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 06.2009 — I've simplified the entire thing and added some SQL injection preventative measures... But I still don't know how to insert another value, if $day is empty.

[code=php]
<?php
require_once('php/conn.php');

if(isset($_POST['submit']))
{
$day = trim($_POST['day']);
$output_form = false;

if(isset($_POST['day']) && !empty($_POST['day']))
{ $connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Problem Connecting') ;
mysqli_select_db($connect, DB_NAME);

$query = "INSERT INTO images (day) VALUES ('$day')" ;
$data = mysqli_query($connect, $query) or die('Problem Inserting');

echo '<h3>Image successfull uploaded</h3>';
echo 'Click here to insert another <a href="manual.php">Manual Upload</a>';

$day = "";
mysqli_close($connect);
}
else { echo 'WHAT AM I DOING WRONG???';}
}

else { $output_form = true; }
[/code]
Copy linkTweet thisAlerts:
@MindzaiDec 07.2009 — You haven't done anything which will protect you against SQL injection. All trim() does is remove any whitespace from the start and end of the string.

By reassigning variables I mean this:

[code=php]
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$title = $_POST['title'];
$sender = $_POST['sender']; [/code]


All it does is complicate things introduce more areas for error.

To set defaults you can just check if the field was posted and filled in, and if not set your default. This is what the code I posted above does:

[code=php]$_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? $_POST['day'] : date('d');
$_POST['month'] = isset($_POST['month']) && !empty($_POST['month'] ? $_POST['month'] : date('m');
// etc[/code]
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — You haven't done anything which will protect you against SQL injection. All trim() does is remove any whitespace from the start and end of the string.

By reassigning variables I mean this:

[code=php]
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$title = $_POST['title'];
$sender = $_POST['sender']; [/code]


All it does is complicate things introduce more areas for error.

To set defaults you can just check if the field was posted and filled in, and if not set your default. This is what the code I posted above does:

[code=php]$_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? $_POST['day'] : date('d');
$_POST['month'] = isset($_POST['month']) && !empty($_POST['month'] ? $_POST['month'] : date('m');
// etc[/code]
[/QUOTE]


Hmmm... Ok. Guess I will have to read that chapter on SQL injections again.

I see where you're going with this. Makes sense... I couldn't find any reference to it on the web though. Got a link I could investigate further?

Tell me... Why on earth do all 3 text books I am learning from & use as a reference, don't tell us to do it that way? Unless that's just a more advanced way & I haven't reached those chapters yet!

:p
Copy linkTweet thisAlerts:
@MindzaiDec 07.2009 — The code you originally posted:

[code=php]if(empty($month))
{ $month == date('F'); }
else { $month = $_POST['month']; }[/code]


is the same idea, just implemented wrong.

$month == date('F'); is saying "is the result of the date('F') function equal to the contents of the $month variable?". The == operator is for checking equality, not assignment. So if $month is empty what you are inserting into your db is not the result of the $date function but the boolean value false.

The code I gave you is just a shorthand way of writing the same thing (minus errors and reassignment of variables ?). You could also do it like this:

[code=php]if (!isset($_POST['day']) || empty($_POST['day'])) {
$_POST['day'] = date('d');
}[/code]


Note that I use isset() first. Because expressions are evaluated from left to right, if the $_POST['day'] variable is not set at all, it will be set with the default as the condition will immediately fail. This avoids a notice level error which you would get from trying to check if it is empty() when it is not set. In practice, it's unlikely that a value will not be set since it is part of the form, but you can never assume that your script will receive data from your form, I think it's always better to code defensively. It's also a good habit to get into because certain form elements such as checkboxes do not form part of the $_POST array unless they are checked.
Copy linkTweet thisAlerts:
@SrWebDeveloperDec 07.2009 — @OP:

Tell me... Why on earth do all 3 text books I am learning from & use as a reference, don't tell us to do it that way? Unless that's just a more advanced way & I haven't reached those chapters yet![/QUOTE]

Mindzai worded it perfectly - defensive programming. This involves techniques that derive from experience. The textbooks often reference older versions of PHP or often include "simplified" forms of code blocks to explain a concept more than focusing on security and defensive practices. I know you're asking a rhetorical question, and yes, in time you'll see more of these techniques popping up in well written code.

-jim
Copy linkTweet thisAlerts:
@apegDec 07.2009 — A while back I found a function for DB insertion that has treated me well over the years:

[CODE]function mysql_insert_array($data, $table = 'users') {
include($_SERVER['DOCUMENT_ROOT'].'/includes/vit.php');
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die();
foreach ($data as $field=>$value) {
$fields[] = '' . $field . '';
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$field_list = join(',', $fields);
$value_list = join(', ', $values);

$query = "INSERT INTO " . $table . " (" . $field_list . ") VALUES (" . $value_list . ")";

if (mysql_query($query)) return true;
return false;
}[/CODE]


You need to give it the user/pass for your DB (1st & 2nd line of the function), I saw a long time ago that you should always keep that information in a separate file (don’t know if there is any reasoning to that, but I do)

From there the function will take care of rest, just pass it an array.

[CODE]$ary = array(
'user_name'=>$_POST['username'],
'password'=>$_POST['password'],
'first_name'=>$_POST['first'],
'last_name'=>$_POST['last'],
'phone'=>$_POST['phone'],
'email'=>$_POST['email'],
'paymentTag'=>false);
mysql_insert_array($ary);[/CODE]


For your empty() issue most of the solution from other posts will work just fine, test -> edit the value accordingly before putting it into the array.

*this is only for new DB entries, for updating you can still use this but a few things will need to be changed.

-aPeG
Copy linkTweet thisAlerts:
@MindzaiDec 07.2009 — The only part of that function needed in this case is the mysql_real_escape string (though in this case since the OP is using mysqli prepared statements would be an even better option). Otherwise the function is not really very efficient since it creates a whole new connection every time it's called plus it localizes the db config when really it should be decentralized.
Copy linkTweet thisAlerts:
@apegDec 07.2009 — Shoot I didn&#8217;t even notice the mysqli call&#8230; I have to read the posts better.

The function could defiantly use some work, just thought I would throw out a simple (not the best) solution.
Copy linkTweet thisAlerts:
@SrWebDeveloperDec 07.2009 — @OP:

In future projects consider writing a connection class as part of a slim database abstraction layer. In English this refers to a concept of software design for your overall project where the database code is separate from other code. This provides you with the ability to support multiple database servers and preserve the syntax and power of SQL as much as possible, while letting class functions build queries differently for different servers/database formats. Plus the class will provide basic security checks like SQL injection prevention. You can port the layer to other projects easily, saving valuable development time.

Start looking into database classes written in PHP if you wish to learn about some of these more advanced concepts as mentioned by other users here.

I suggest visiting phpclasses.org and searching for "database".

-jim
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — Mindzai:
$month == date('F'); is saying "is the result of the date('F') function equal to the contents of the $month variable?". The == operator is for checking equality, not assignment. So if $month is empty what you are inserting into your db is not the result of the $date function but the boolean value false.[/QUOTE]
Ooook... I get it now.
The code I gave you is just a shorthand way of writing the same thing (minus errors and reassignment of variables ?). Note that I use isset() first. Because expressions are evaluated from left to right.[/QUOTE]
Duly noted...

SrWebDeveloper: So... With regards to coding defensively, I guess what I have to do is write code as if Every One is out to get me. Hehe... It seems the only way to learn this, as it isn't quiet as "basic" as learning HTML or CSS, is by repetition and making mistakes. Just have to code, code, code...
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — Apeg: Thanks for that... I will copy it and play around with it. Although I still need to learn or get to the point in my Current Book that uses $_SERVER['DOCUMENT_ROOT'], mysqli_insert_array(); Those are currently the first time I am seeing them ?

I consider it good practice, or so I am told (LoL) to use a separate file for connection variables anyways, usually a connect.php page and then just require_once(); it in...
[code=php]
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','*****');
define('DB_NAME','database_name');
[/code]
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — Question: OP???
Copy linkTweet thisAlerts:
@SrWebDeveloperDec 07.2009 — Question: OP???[/quote]

Original Post or Original Poster
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — Original Post or Original Poster[/QUOTE]

Now I am in with the Lingo. LoL... Will keep this thread updated with my progress.
Copy linkTweet thisAlerts:
@SrWebDeveloperDec 07.2009 — SrWebDeveloper: So... With regards to coding defensively, I guess what I have to do is write code as if Every One is out to get me. Hehe... It seems the only way to learn this, as it isn't quiet as "basic" as learning HTML or CSS, is by repetition and making mistakes. Just have to code, code, code...[/quote]

It's the mistakes that make you wise. Plus a thousand other cliche's! :p
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — It's the mistakes that make you wise. Plus a thousand other cliche's! :p[/QUOTE]

Bwhahahahaha... Don't even get me started on cliches. ?
Copy linkTweet thisAlerts:
@svidgenDec 07.2009 — I consider it good practice, or so I am told (LoL) to use a separate file for connection variables anyways, usually a connect.php page and then just require_once(); it in...[/QUOTE]
True statement. And ideally this connection file is located outside the document root and is accessibly only by www/apache and privileged developers (you and w/e co-developers [B]need[/B] access).
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 07.2009 — True statement. And ideally this connection file is located outside the document root and is accessibly only by www/apache and privileged developers (you and w/e co-developers [B]need[/B] access).[/QUOTE]

I usually put all my php required/include files in one or two folders, all in the main directory. Eg... root/home/php or root/x/ or root/php/inclu etc...

Where else would I place it, outside the root?

When placing it online, would I place it in another domain? Or Server?

?
Copy linkTweet thisAlerts:
@svidgenDec 08.2009 — Suppose you have a virtualhost pointed at [B]/home/kermitthefrog/public_html[/B]. You might use [B]/home/kermitthefrog/secure_includes/php[/B] for your secure PHP includes. I personally think it's good practice to avoid putting these types of includes anywhere in the general include path--it makes them easily locatable by other users' code or code from other sites (presuming a shared box or box hosting multiple sites).
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 08.2009 — Thanks svidgen... Will check it out.
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 08.2009 — I am a CIW Web Design part time student, in the UK. (Bit of useless info for you all. ?) And PHP/MySQL I do in my own time... Anyways, I just busy studying my JavaScript text book and came across this

[CODE]
JavaScript Operators:

(condition) ? value1 : value 2

[/CODE]


Am I wrong in saying that this is the same "shorthand" technique that was discussed earlier with regards to PHP?

[code=php]
$_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? $_POST['day'] : date('d');[/code]


(condition/s) ? val 1 : val 2 ;

What does the ? represent. Coz = is not "equal to", it's "is set" eg: x "is set" to 5 (x=5)
Copy linkTweet thisAlerts:
@MindzaiDec 08.2009 — ?: is called the ternary operator and it's common in most C style languages (C, java, js, PHP etc).

It works like an inline if statement - if condition is true then x else y. It just evaluates to one of the 2 values depending on the condition, nothing more complicated than that.

You can use the assignment operator (=) to assign the evaluated result to a variable, or you can use it directly (with return or echo for example).
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 08.2009 — ?: is called the ternary operator and it's common in most C style languages (C, java, js, PHP etc).

It works like an inline if statement - if condition is true then x else y. It just evaluates to one of the 2 values depending on the condition, nothing more complicated than that.

You can use the assignment operator (=) to assign the evaluated result to a variable, or you can use it directly (with return or echo for example).[/QUOTE]


NNNNNIIIIIIICCCCCEEEEEEE.... I like it ?
Copy linkTweet thisAlerts:
@svidgenDec 09.2009 — Not sure why, but I really don't like the ternary "operator." I almost always use an if() block ...
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 09.2009 — Not sure why, but I really don't like the ternary "operator." I almost always use an if() block ...[/QUOTE]

It all comes down to personal preference and what works for you and adopting a style that that you are comfortable with. Because I am such beginner, I am still trying to find "my feet" so will be trying out multiple styles ?
Copy linkTweet thisAlerts:
@MindzaiDec 09.2009 — The ternary operator does have a certain ugliness about it I agree. I do use it out of laziness as much as anything but I'm not a big fan.
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 09.2009 — Ugliness???
Copy linkTweet thisAlerts:
@MindzaiDec 09.2009 — Which is more pleasing and easy to read to you? This:

[code=php]$_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? date('m') : date('d');[/code]

or this:

[code=php]if (isset($_POST['day']) && !empty($_POST['day'])) {
$_POST['day'] = date('m');
} else {
$_POST['day'] = date('d');
}[/code]


Personally I think the second one is "nicer", but as I mostly only read my own code, and I can read the ternary version just as well, I use the ternary form out of laziness. If I was writing code which I ever expected to be maintained by someone other than myself I would probably avoid it more than I do.
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 09.2009 — As it stands now (and I am doing some practicing code as we speak) I prefer the short hand version. If it were to be maintained by someone else, I might just add a short comment as to what it does.

But, currently, the only code I write is for myself and my own needs. I do this as a hobby (hopefully more some day) Maybe when that day comes, I will take other people into consideration and stick to the more accepted way of writing it. Hehe...
Copy linkTweet thisAlerts:
@MindzaiDec 09.2009 — I wouldn't bother with "what it does comments" if I were you - anyone reading your code can probably understand the PHP syntax. Useful comments are more "why its done like this". Again just my opinion, but I cringe when I see things like this:

[code=php]
// add one to $x
$x++;
[/code]
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 09.2009 — [code=php]$_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? $_POST['day'] : date('d'); [/code] Doesn't seem to like echo...

[code=php]$_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? echo $_POST['day'] : echo date('d'); [/code]

I get an error... Well, the page doesn't even load. If I take out echo, it loads, but how do I echo the results? Assign it to a variable and echo that??? Hmmm.... *ponders*

This works:

[code=php]$_POST['day'] = isset($_POST['day']) && !empty($_POST['day']) ? $day1 = $_POST['day'] : $day1 = date('d') ;
echo "$day1" ;[/code]
Copy linkTweet thisAlerts:
@criterion9Dec 09.2009 — [code=php]
echo $_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? $_POST['day'] : date('d');
[/code]
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 09.2009 — [code=php]
echo $_POST['day'] = isset($_POST['day']) && !empty($_POST['day'] ? $_POST['day'] : date('d');
[/code]
[/QUOTE]


Bwhahahaha... ? So simple. Tried it your way and mine. Got them both working. Your way is neater though.
Copy linkTweet thisAlerts:
@MindzaiDec 09.2009 — You need to remember that ?: is an operator, ie it forms part of an expression. This means it evaluates to a value, which you can then echo, assign to a variable etc.

You were trying to use it as a structural element like an if ... else ... block - this is an understandable mistake (I made it too first time I saw the ternary operator) but if you remember that it is an operator in an expression hopefully its clear why criterion's syntax works.
Copy linkTweet thisAlerts:
@NogDogDec 09.2009 — Just a side-note, you don't have to have a ternary expression all on one line, which may add in readability:
[code=php]
$foo =
isset($_POST['foo']) ?
trim($_POST['foo']) :
'bar'
;
[/code]
Copy linkTweet thisAlerts:
@Hooded_VillianauthorDec 09.2009 — NogDog: Thanks for the tip. That one I was actually aware off. ?

MindZai: I was just learning about expressions and operators for JavaScript, so it actually makes sense. Thanks. (Murphys Law, I am bound to make the same mistake again, except using something else, other than echo. Hahaha.) On an on I go, till I get it right!!!
Copy linkTweet thisAlerts:
@svidgenDec 10.2009 — Of course, if you're splitting it across multiple lines, you may as well use an IF block :p
Copy linkTweet thisAlerts:
@NogDogDec 10.2009 — Of course, if you're splitting it across multiple lines, you may as well use an IF block :p[/QUOTE]

You could, but depending on your personal preferences and experience, you might in fact find the ternary version easier to read, as it's still a bit more compact and does not require duplication of the assignment statement (or whatever you want to do):
[code=php]
$foo =
isset($_POST['foo']) ?
trim($_POST['foo']) :
'bar'
;
[/code]

[code=php]
if(isset($_POST))
{
$foo = trim($_POST['foo'];
}
else
{
$foo = 'bar';
}
[/code]

I'm certainly not going to complain whichever way you want to use (and I can't say that I consistently favor either one). I just hate trying to read anybody's code when they have one of those ternary one-liners where that line is about 150 characters long, so I have to call out a search party to find the "?" and the ":". :rolleyes:
Copy linkTweet thisAlerts:
@svidgenDec 10.2009 — I just hate trying to read anybody's code when they have one of those ternary one-liners where that line is about 150 characters long, so I have to call out a search party to find the "?" and the ":". [/QUOTE]
Agreed.
×

Success!

Help @Hooded_Villian spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...