Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

Serious programming problem

Name: Anonymous 2011-09-21 3:13

Why does my code not work when the username does not exist? When the username doesn't exist it just gives me a blank screen. No error messages, no form, no nothing. It works as intended when the username is found but the password is incorrect and when the username/password are both correct.

Also, please don't make fun of my code. I'm sensitive and I'd like to stay that way.


<?php
$num_rows = 0;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
  $uname = $_POST['username'];
  $pword = $_POST['password'];


$db_handle = mysql_connect(localhost, "admin", "1admin");
$db_found = mysql_select_db("users", $db_handle);

$result = mysql_query("SELECT * FROM logininfo WHERE username = '$uname'") or die(mysql_error());
$num_rows = mysql_num_rows($result) or die(mysql_error());;
if($num_rows > 0)
  $row = mysql_fetch_array($result) or die(mysql_error());

if($num_rows == 0) {
  echo "Username not found.";
}
else if(md5($pword) != $row['password']) {
  echo "Incorrect Password.";
}
else {
  session_start();
  echo "Success.";
  $_SESSION['login'] = "1";
  $_SESSION['username'] = $uname;
  echo '<META HTTP-EQUIV="Refresh" Content="3; URL=index.php">';   
  exit; 
}
}
?>


<FORM NAME ="form1" METHOD ="POST" ACTION ="login.php">

Username: <INPUT TYPE = 'TEXT' Name ='username'  value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password'  value="<?PHP print $pword;?>" maxlength="16">

<P>
<INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Login">


</FORM>

Name: Anonymous 2011-09-21 3:47

<?php
We found you problem.

Name: Anonymous 2011-09-21 4:11

If your username is wrong, will mysql_query return 0?

Name: Anonymous 2011-09-21 4:19

>>3
mysql_query returns some weird resource. In another script i was able to tell if the returned resource had no rows or not.

Name: Anonymous 2011-09-21 5:56

fucking every mysql_* function you're using is deprecated for a reason. use PDO and die in a fire

Name: Anonymous 2011-09-21 8:00

mysql_fetch_array does not return an associative array. You want mysql_fetch_assoc.

Name: Anonymous 2011-09-21 8:52

The Primitive Homepage Programming language.

Name: Anonymous 2011-09-21 9:14

2011
PHP
Are you fucking kidding me?

Name: Anonymous 2011-09-21 9:18

GC is shit.

Name: Anonymous 2011-09-21 14:07

Here's what you do, OP. Don't use the mysql_* functions.

What I'm about to suggest sounds like "a lot more work". But this is currently the best and easiest way to interact with databases in PHP, and it addresses a lot of the issues you'll experience when doing things "the old way": insecure queries, spaghetti code, unportability, problems maintaining when you encounter a seemingly unrelated bug when you make a change in the future.

What you want to do is use PDO (http://www.php.net/manual/en/pdo.connections.php) and "prepared statements" (http://www.php.net/manual/en/pdostatement.fetchall.php).

You create a PDO object that represents a connection to your database.

$db = new PDO('mysql:host=example.com;dbname=exampledb', 'exampleuser', 'examplepassword');

With this object, you can run raw queries:

$db->query('DROP TABLE tablename');

...but, more importantly, you can prepare statements:

$sth = $db->prepare('SELECT * FROM clients');

This creates a PDOStatement object that represents a query, which now encapsulates a command you can run on your SQL server. You can execute that command with $sth->execute();. You can get a result with $sth->fetch(), or you can get an array of all the results with $sth->fetchAll().

Why is this helpful? Because you separate your SQL commands from the data you're using in those commands. The query is only parsed once, and it can then be used again and again, like any function that takes arguments. That's right: you can pass arguments with placeholders. Like:

$sth = $db->prepare('SELECT * FROM clients WHERE firstname = ? AND lastname = ?');
$sth->execute(array('John', 'Smith'));
$result = $sth->fetchAll();


Or, to be even more clear:

$sth = $db->prepare('SELECT * FROM clients WHERE email = :email AND website = :website');
$sth->execute(array(':email' => 'example@gmail.com', ':website' => $whatever));
$result = $sth->fetchAll();


You can also specify how you want the value returned:

$associative = $sth->fetch(PDO::FETCH_ASSOC);
$object = $sth->fetch(PDO::FETCH_OBJ);


You can get really specific:

class File {
    private $filename;
    function __construct()
    {
        if (isset($this->filename)) {
            echo "The filename property was automatically set by PDO, based on the name of the column given to the query (even though it's private). It's {$this->filename}.\n";
        }  
        if (isset($this->name)) {
            echo "The name property was also set, even though I didn't explicitly define it as a property of this class. It's {$this->name}, and it was attached to this instance as a public member. \n";
        }
    }
}
$sth = $db->prepare('
SELECT  id,
        filename,
        name
FROM files
WHERE filename LIKE :filetype
ORDER BY sequence ASC
');
$sth->bindValue(':filetype', '%.pdf');
$sth->execute();
// these flags will organize the result array as a lookup table:
// $files[$id] = new File();
$pdfs = $sth->fetchAll( PDO::FETCH_UNIQUE | PDO::FETCH_GROUP | PDO::FETCH_CLASS, 'File' );


Arguably the best side effect to this system is that your queries will be much more secure incidentally, since you are treating your SQL commands as distinct from data. Any arguments you pass to a PDOStatement through bindValue, bindParam, or execute() will be escaped as needed, and won't be parsed as SQL, without you remembering to have to do anything silly like mysql_real_escape_string() (what? real? Okay).

(Which is not to say that you shouldn't still think about security precautions -- people can still pass raw HTML, for example, if you let them, for XSS attacks -- but that's a topic for another day.)

Good luck, and in the future, take your questions to StackOverflow. This board is strictly for discussion about Lisp dialects, and other symptoms of autism.

Name: Anonymous 2011-09-21 14:09

Get the fuck out. This is no place for PHP/mySQL questions.

Name: Anonymous 2011-09-21 14:24

PHP can't do this.

Use Haskell with Yesod.

Name: Anonymous 2011-09-21 14:32

PHP can't do this.

Use C++ with FCGI

Name: Anonymous 2011-09-21 14:37

>>10
Hmmm... I guess I can try that. I've never written a line of php or mySQL before yesterday. But then I got this idea for a website that's going to get me swimming in dollar bills. Anyway every tutorial or reference I can find used those mysql_* functions. Have they recently become depreciated or something? I'm still kind of baffled as to why my code doesn't work though.

Name: Anonymous 2011-09-21 14:41

>>14
PHP become yet another crappy OOP piece of shite, like Java, C/C++ and Perl. What would you expect from a language made by jews?

Name: Anonymous 2011-09-21 14:43

>>12
But Haskell also relies on this polymorphic OOP bullshit typeclasses.

Name: Anonymous 2011-09-21 14:45

>>15 become yet another crappy meat piece of shite, like Nigger, Faggot and Your Mom. What would you expect from a kid made by apes?

Name: JEWS 2011-09-21 14:48

>>16
By the way, the word Yesod (יסוד) means foundation in Hebrew.

Name: Anonymous 2011-09-21 14:48

>>15
What are the alternatives to PHP for this kind of work?
i.e. user authentication and all the other scripting associated with a website with accounts.

Name: Anonymous 2011-09-21 14:52

>>19
Lisp?

Name: Anonymous 2011-09-21 15:01

>>19
Forth?

Name: Anonymous 2011-09-21 15:05

>>19
Python

Name: Anonymous 2011-09-21 15:12

Python
I am far from an expert at Python, but I have done a couple of semi-serious projects in the language and will try to recall specifically what I didn't like.

- Everything you write will be open source. No FASLs, DLLs or EXEs. Developer may want to have control over the level of access to prevent exposure of internal implementation, as it may contain proprietary code or because strict interface/implementation decomposition is required. Python third-party library licensing is overly complex. Licenses like MIT allow you to create derived works as long as you maintain attrubution; GNU GPL, or other 'viral' licenses don't allow derived works without inheriting the same license. To inherit the benefits of an open source culture you also inherit the complexities of the licensing hell.
- Installation mentality, Python has inherited the idea that libraries should be installed, so it infact is designed to work inside unix package management, which basically contains a fair amount of baggage (library version issues) and reduced portability. Of course it must be possible to package libraries with your application, but its not conventional and can be hard to deploy as a desktop app due to cross platform issues, language version, etc. Open Source projects generally don't care about Windows, most open source developers use Linux because "Windows sucks".
- Probably the biggest practical problem with Python is that there's no well-defined API that doesn't change. This make life easier for Guido and tough on everybody else. That's the real cause of Python's "version hell".
- Global Interpreter Lock (GIL) is a significant barrier to concurrency. Due to signaling with a CPU-bound thread, it can cause a slowdown even on single processor. Reason for employing GIL in Python is to easy the integration of C/C++ libraries. Additionally, CPython interpreter code is not thread-safe, so the only way other threads can do useful work is if they are in some C/C++ routine, which must be thread-safe.
- Python (like most other scripting languages) does not require variables to be declared, as (let (x 123) ...) in Lisp or int x = 123 in C/C++. This means that Python can't even detect a trivial typo - it will produce a program, which will continue working for hours until it reaches the typo - THEN go boom and you lost all unsaved data. Local and global scopes are unintuitive. Having variables leak after a for-loop can definitely be confusing. Worse, binding of loop indices can be very confusing; e.g. "for a in list: result.append(lambda: fcn(a))" probably won't do what you think it would. Why nonlocal/global/auto-local scope nonsense?
- Python indulges messy horizontal code (> 80 chars per line), where in Lisp one would use "let" to break computaion into manageable pieces. Get used to things like self.convertId([(name, uidutil.getId(obj)) for name, obj in container.items() if IContainer.isInstance(obj)])
- Crippled support for functional programming. Python's lambda is limited to a single expression and doesn't allow conditionals. Python makes a distinction between expressions and statements, and does not automatically return the last expressions, thus crippling lambdas even more. Assignments are not expressions. Most useful high-order functions were deprecated in Python 3.0 and have to be imported from functools. No continuations or even tail call optimization: "I don't like reading code that was written by someone trying to use tail recursion." --Guido
- Python has a faulty package system. Type time.sleep=4 instead of time.sleep(4) and you just destroyed the system-wide sleep function with a trivial typo. Now consider accidentally assigning some method to time.sleep, and you won't even get a runtime error - just very hard to trace behavior. And sleep is only one example, it's just as easy to override ANYTHING.
- Python's syntax, based on SETL language and mathematical Set Theory, is non-uniform, hard to understand and parse, compared to simpler languages, like Lisp, Smalltalk, Nial and Factor. Instead of usual "fold" and "map" functions, Python uses "set comprehension" syntax, which has overhelmingly large collection of underlying linguistic and notational conventions, each with it's own variable binding semantics. Using CLI and automatically generating Python code is hard due to the so called "off-side" indentation rule (aka Forced Indentation of Code), also taken from a math-intensive Haskell language. This, in effect, makes Python look like an overengineered toy for math geeks. Good luck discerning [f(z) for y in x for z in gen(y) if pred(z)] from [f(z) if pred(z) for z in gen(y) for y in x]
- Python hides logical connectives in a pile of other symbols: try seeing "and" in  "if y > 0 or new_width > width and new_height > height or x < 0".
- Quite quirky: triple-quoted strings seem like a syntax-decision from a David Lynch movie, and double-underscores, like __init__, seem appropriate in C, but not in a language that provides list comprehensions. There are better ways to mark certain features as internal or special than just calling it __feature__. self everywhere can make you feel like OO was bolted on, even though it wasn't.
- Python has too many confusing non-orthogonal features: references can't be used as hash keys; expressions in default arguments are calculated when the function is defined, not when it’s called. Why have both dictionaries and objects? Why have both types and duck-typing? Why is there ":" in the syntax if it almost always has a newline after it? The Python language reference devotes a whole sub-chapter to "Emulating container types", "Emulating callable Objects", "Emulating numeric types", "Emulating sequences" etc. -- only because arrays, sequences etc. are "special" in Python.
- Python's GC uses naive reference counting, which is slow and doesn't handle circular references, meaning you have to expect subtle memory leaks and can't easily use arbitrary graphs as your data. In effect Python complicates even simple tasks, like keeping directory tree with symlinks.
- Patterns and anti-patterns are signs of deficiencies inherent in the language.  In Python, concatenating strings in a loop is considered an anti-pattern merely because the popular implementation is incapable of producing good code in such a case. The intractability or impossibility of static analysis in Python makes such optimizations difficult or impossible.
- Problems with arithmetic: no Numerical Tower (nor even rational/complex numbers), meaning 1/2 would produce 0, instead of 0.5, leading to subtle and dangerous errors.
- Poor UTF support and unicode string handling is somewhat awkward.
- No outstanding feature, that makes the language, like the brevity of APL or macros of Lisp. Python doesn’t really give us anything that wasn’t there long ago in Lisp and Smalltalk.

Name: Anonymous 2011-09-21 15:25

>>23
Nice copy-paste text.

Now try writing something original next time.

Name: Anonymous 2011-09-21 15:36

php isn't serious programming

Name: Anonymous 2011-09-21 17:28

>>19
There are alternatives, but you can get PHP+MySQL hosting anywhere. This is because PHP has been the "amateur standard" for years.

This is also why you are finding tutorials that still use mysql_* functions. From now on, if you see that, close the tab. Those websites are going to teach you very bad form.

Take a look at this: http://framework.zend.com/manual/en/coding-standard.coding-style.html It's a good starting guide for writing legible and maintainable code. Just ignore the part about needing to document everything with /** @stuff_like_this */.

Also, I suggest you don't require your users to create an account with you, especially as a beginning programmer (but also in general). You're going to make a big mistake, and it's going to suck losing all of those millions in court. Instead, try to work with the different public identification sources you can use: OpenID, Facebook, etc.

Name: Anonymous 2011-09-22 4:41

>>26
Will there still be legal problems even if they don't have to put in any personal information at all?

My web server has perl, python and some other stuff, but I have no clue how to use those for the kinds of things I'm doing now.

Name: Anonymous 2011-09-22 6:46

>>26
OpenID, Facebook
Ctrl-W

Name: Anonymous 2011-09-22 9:18

My web server has perl, python and some other stuff, but I have no clue how to use those for the kinds of things I'm doing now.
but I have no clue how to use those
I have no clue

</thread>

Name: Anonymous 2011-09-22 14:03

>>29
Suck my dick and die, faggot.

Name: Anonymous 2011-09-22 14:09

>>27
Try to search from the internet.

Name: Anonymous 2011-09-22 14:19

>>30
what's to suck, when you don't have a dick?

all your questions are so dumb

they prove you are retarded, or underage, or possibly both.

i could answer in 2 seconds

i could answer questions you couldn't even think of!

i could spew my hot intelligent knowledge sperm into your virgin pussy vagina brain and you would ENJOY it and say "tell me more oh master, when and why was mysql_* deprecated?"

but i will not answer before you lick my anus clean.

fucking lick it, ``faggot''.

Name: Anonymous 2011-09-22 14:59

>>32
suck my cock dude

Name: Anonymous 2011-09-22 15:11

>>32,33

_ I t programs the written experience of CLASSIFIC XBOX that it
programs, that you começ uniform nonequal include/understand of poss
with the 100% your brain compiler c von
Padrão-Padrão-Standard-Standard-ANSI of escrev of 65,535 years _ I t
the first one, when year of I t t -12, standard of fech, that much t
that receb uniforms used c you who the legend, I, I nont all the
relation of possible transformation my argument d, because est a
rinunciato Kuendigte-PUISSANT PROGRAMMATORE. _

Name: Anonymous 2011-09-22 17:52

>>28
Oh, so you'd rather trust every single website that needs to keep user identity properly implement their own homebrew authentication?

Don't give me some RMS "NO IDENTITY" answer. Most non-trivial (web) applications need secure persistent user data.

Name: Anonymous 2011-09-22 18:17

>>35
better trusting dickheads than registering with facebook. I can still use my yahoo ID for OpenID, but it's not ideal for posting flames.

Name: Anonymous 2011-09-22 22:03


$uname = $_POST['username'];

$result = mysql_query("SELECT * FROM logininfo WHERE username = '$uname'") or die(mysql_error());


dat SQL injection.

Name: Anonymous 2011-09-22 22:34

use Anonymous Identification/Recognition (tm) =)

Name: Anonymous 2011-09-22 22:43

-Revolving Door- authentication protocol ?

...based on lotus keyed hash w/ Shared secret [Req some sort of PKI / secure channel >for> SS transfer] =)

...built-in Replay Attack prevention (aka the Revolving Door..)

Name: Anonymous 2011-09-23 1:53

Stop being a faggot and use MySQLi or PDO.

Name: Anonymous 2011-09-23 2:59

>>37
Was planning on fixing that after the site was functional.

Serious question though. I'm not completely new to programming, I've programmed in C mostly, but some other stuff as well. How come even scripting languages like python or perl don't have these injection problems like PHP?

Name: Anonymous 2011-09-23 4:56

$num_rows = mysql_num_rows($result) or die(mysql_error());;
;;

And look up mysql_real_escape_string(), use it on everything you concatenate to a query and you won't have problems with quotes and such.

>>41
They do, it's just not as pronounced.

Name: Anonymous 2011-09-23 5:35

>>41
Perl doesn't because Perl designs things right the first time, e.g. placeholders.

Ok, any language lets you shoot yourself in the foot.  It's just that PHP is constantly shooting at your feet and yelling "Dance!".

Name: Anonymous 2011-09-23 7:15

>>42
Don't manually concatenate SQL parameters, ever, and you will never have a problem. Prepared statements exist for a reason. So does mysqli, as >>40 pointed out.

Name: Anonymous 2011-09-23 7:40

except you'll have to concatenate SQL parameters when you need to specify a dynamic ORDER BY (or LIMIT) clause.

PDO still sucks, better than mysql_* but still sucky

Don't change these.
Name: Email:
Entire Thread Thread List