-5

So trying to insert some data from a PHP page into my SQL database. This page is ONLY accessible via myself so I'm not worried about it being accessed or SQL injectable etc. My issue is no matter what code I use it doesn't go into the database. I've tried coding it myself, using template codes, taking from php.net etc nothing has worked!

It now redirects me with the success message but still nothing in the database.

Code will be put below and I'll edit some of my details for privacy reasons.

<?php
require connect.php

   // If the values are posted, insert them into the database.
    if (isset($_POST['username']) && isset($_POST['password'])){
        $username = $_POST['username'];
        $isadminB = $_POST['isadmin'];
        $password = $_POST['password'];

        $query = "INSERT INTO `users` (user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
        $result = mysql_query($query);
        if($result){
            $msg = "User Created Successfully.";
        }
    }
    $link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

The echo mysql_errno($link) . ": " . mysql_error($link). "\n"; was the code that gave me error code 0?

As requested the code for the form from my previous page.

<form action="account_create_submit.php" method="post">
Username: <input type="text" name="username" id="username"> <br /><br />
Password: <input type="password" name="password" id="password"> <br /><br />
<span id="isadmin">Is Admin: Yes<input type="radio" name="isadmin" id="1" value="1"> | No<input type="radio" name="isadmin" id="0" value="0"><br /></span>
<span id="submit"><input type="submit" value="Create Account"></span>
</form>

Ok so changed the form code so method is now POST. Great! All data is being read correctly although that wasn't my issue as even typing in hard data for the code to submit wasn't working at least its a future issue resolved already. The new error code is no longer 0 but rather the following:

1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user_name', 'password', 'isadmin') VALUES ('testZ', 'lol', '1')' at line 1

Connect.php

    <?php
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB');
if (!$select_db){
    die("Database Selection Failed" . mysql_error());
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Brad Andrews
  • 106
  • 1
  • 1
  • 11
  • 3
    Do yourself a favor and migrate to PDO instead of using **deprecated** mysql_* functions. – Charlotte Dunois Aug 30 '15 at 20:36
  • 1
    Please help the question at hand. I'm sure other users may also be having similar problems with MySQL. Rather than just saying migrate to PDO why not help? Or better yet give me more details about PDO and how I'd switch and how that would help? – Brad Andrews Aug 30 '15 at 21:57
  • Brad, I'll put in bluntly, but don;t take it personally. This is a poor example of code. You are using functions that are deprecated; you are storing password in an insecure manner, You are doing no validations on the data. You are connecting to the db AFTER your query. Your $msg value is going nowhere. No wonder you are having issues. Fix up this code please. – crafter Aug 30 '15 at 23:41
  • 4
    I'm not saying his code is written well but mysql was good for its time. Lets just stop saying that using deprecated functions is bad code. Thats just like saying computers from 1985-1995 were bad because they were not as good as computers today. – benlevywebdesign Aug 30 '15 at 23:46
  • you're attempting to query before connecting – Funk Forty Niner Aug 31 '15 at 00:09
  • @Fred-ii- can you elaborate? I believe it is connected... Otherwise it'd be giving a different error? I've tried many different ways of connecting and different lines of code too... Nothing seems to work? – Brad Andrews Aug 31 '15 at 00:15
  • Let's see connection.php. – tllewellyn Aug 31 '15 at 00:16
  • 1
    Ok so I've tried to get it to work using connection.php and tried hard coding it into the page itself. Seems I'm getting more luck hardcoding. So my guesses the connect.php has the majority of problems. Will add to OP now @tllewellyn – Brad Andrews Aug 31 '15 at 00:18
  • I posted an answer for you below using `mysqli_` with prepared statements. No sense in having everyone else guessing. Plus, make sure your column lengths are long enough and are the correct type. – Funk Forty Niner Aug 31 '15 at 00:24
  • You're missing the link identifier in the mysql_select_db statement. It should be $select_db = mysql_select_db('Default_DB', $connection); – tllewellyn Aug 31 '15 at 00:26
  • Then change $result = mysql_query($query) to $result = mysql_query($query, $connection); – tllewellyn Aug 31 '15 at 00:27
  • You should check out @Hkan answer and accept it if it fixes your issue. – Aziz Saleh Aug 31 '15 at 00:41
  • @AzizSaleh oh and why is that? think I didn't work enough on this question and to know better? right. see my comment under his answer. get your facts straight here people. – Funk Forty Niner Aug 31 '15 at 00:54
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Aug 31 '15 at 12:03
  • If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) [statements](http://php.net/manual/en/pdo.prepared-statements.php) instead, and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Aug 31 '15 at 12:03
  • You really shouldn't use MD5 password hashes and you really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). – Jay Blanchard Aug 31 '15 at 12:03

4 Answers4

4

Firstly, for those of you getting the misconception about password for a column name:

Sure, it's MySQL "keyword", but not a "reserved" word; more specifically, it is a function (see ref). Notice there is no (R) next to the "function (keyword) name": https://dev.mysql.com/doc/refman/5.5/en/keywords.html therefore it's perfectly valid as a column name.

Ref: https://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password

Ticks are only required if it is used in order to prevent it from being recognized as a "function", which it clearly is not in the OP's case. So, get your information and facts straight.

More specifically, if a table named as PASSWORD and without spaces between the table name and the column declaration:

I.e.: INSERT INTO PASSWORD(col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')

which would throw a syntax error, since the table name is considered as being a function.

Therefore, the proper syntax would need to read as

INSERT INTO `PASSWORD` (col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')

(Edit:) To answer the present question; you're using $connection in your connection, but querying with $link along with the missing db variables passed to your query and the quotes/semi-colon I've already outlined here.

That's if you want to get that code of yours going, but I highly discourage it. You're using a deprecated MySQL library and MD5 as you stated. All old technology that is no longer safe to be used, nor will it be supported in future PHP releases.

You're missing a semi-colon here require connect.php and quotes.

That should read as require "connect.php";

You should also remove this:

$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

you're already trying to include a connection file.

Use this in your connection file: (modified, using connection variable connection parameter)

$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB', $connection);
if (!$select_db){
    die("Database Selection Failed" . mysql_error());
}

and pass the $connection to your query as the 2nd parameter.

$result = mysql_query($query, $connection);

Add error reporting to the top of your file(s) right after your opening PHP tag for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.

Also add or die(mysql_error()) to mysql_query().

If that still gives you a hard time, you will need to escape your data.

I.e.:

$username = mysql_real_escape_string($_POST['username'], $connection);

and do the same for the others.

Use a safer method: (originally posted answer)

May as well just do a total rewrite and using mysqli_ with prepared statements.

Fill in the credentials for your own.

Sidenote: You may have to replace the last s for an i for the $isadminB that's IF that column is an int.

$link = new mysqli('localhost', 'root', 'password', 'demo');
if ($link->connect_errno) {
    throw new Exception($link->connect_error, $link->connect_errno);
}

if (!empty($_POST['username']) && !empty($_POST['password'])){
    $username = $_POST['username'];
    $isadminB = $_POST['isadmin'];
    $password = $_POST['password'];

// now prepare an INSERT statement
    if (!$stmt = $link->prepare('INSERT INTO `users` 
          (`user_name`, `password`, `isadmin`) 
           VALUES (?, ?, ?)')) {
        throw new Exception($link->error, $link->errno);
    }

    // bind parameters
    $stmt->bind_param('sss', $username, $password, $isadminB);

        if (!$stmt->execute()) {
            throw new Exception($stmt->error, $stmt->errno);
        }

    }
    
    else{
        echo "Nothing is set, or something is empty.";
    }

I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.

I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.

You can also use this PDO example pulled from one of ircmaxell's answers:

Just use a library. Seriously. They exist for a reason.

Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.

$dbh = new PDO(...);

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);

$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);

And on login:

$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
    if (password_verify($_POST['password'], $users[0]->password) {
        // valid login
    } else {
        // invalid password
    }
} else {
    // invalid username
}
Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Yes I was just thinking it's about time to give up and do a total re-write. I'm certainly NOT storing passwords in plain text haha don't worry! I'm using MD5 with a SALT. Yes could be more secure but this isn't a big security concern for myself as the website will not be a LIVE site more of a private project kind of things. Thanks, I'll re-do the code including your snippet and see how it goes. Will update with results. – Brad Andrews Aug 31 '15 at 00:26
  • @BradAndrews MD5 is MD5, any way you slice it. You may as well start using something that's more of "this century" ;-) Unsafe code makes me shudder. – Funk Forty Niner Aug 31 '15 at 00:27
  • @BradAndrews also, if you're going to use the safer hashing, make your password column as `VARCHAR(255)`. That hash will produce a string that is 60 characters long, but PHP.net recommends 255 in order to accomodate for future hashing methods. Technically speaking, you're missing a semi-colon here `require connect.php` and quotes. That should read as `require "connect.php";` – Funk Forty Niner Aug 31 '15 at 00:30
  • @BradAndrews plus, you're using `$connection` in your connection, but querying with `$link` along with the missing db variables passed to your query and the quotes/semi-colon I've already outlined here. That's if you want to get that code of yours going, but I highly discourage it. You're using a deprecated MySQL library and MD5 as you stated. All old technology that is no longer safe to be used, nor will it be supported in future PHP releases. – Funk Forty Niner Aug 31 '15 at 00:37
  • @BradAndrews I don't want the comments thread to grow too long here, but I've made quite a few edits since my original post. Please reload it and read it in its entirety and very carefully. – Funk Forty Niner Aug 31 '15 at 00:47
  • what the hell is that downvote for? and why the hell did that other answer for `password` get an upvote? give me a fu**ing break – Funk Forty Niner Aug 31 '15 at 00:48
  • Someone came along and downvoted all the answers. Right around the time the first answer from Hkan received a comment (which is now suspiciously deleted). – tllewellyn Aug 31 '15 at 00:50
  • 1
    Fred -ii-, I'll re-upvote your answers if you do mine. Cheers – tllewellyn Aug 31 '15 at 00:51
  • 1
    @tllewellyn Yeah, some fu**ing bozo who knows shit about the word `password` https://dev.mysql.com/doc/refman/5.5/en/keywords.html – Funk Forty Niner Aug 31 '15 at 00:51
  • 1
    The amount of time spent trying to help out the OP... whoever it was is a j@ck***. – tllewellyn Aug 31 '15 at 00:53
  • @tllewellyn the ironic thing of it all, is that I also ticked the word password. lol too funny. Let them downvote to their little heart's desire. TBH, I don't give a flying fu*k, as my ol pappy used to say ;-) – Funk Forty Niner Aug 31 '15 at 00:53
  • 1
    @BradAndrews this is by far the best answer with explanation, Please accept the answer by clicking on the tick right below vote count of this answer! – DirtyBit Sep 02 '15 at 17:37
1

You are using "get" as your form submission method. "post" variables won't be recognized.

Also...

It looks like you're missing the second parameter of your mysql_query() function which is your link identifier to the MySQL connection. I'm assuming you've created the connection in connection.php.

Typically, the mysql_query() function would be

$result = mysql_query($query, $conn);

with $conn having been pre-defined in your connection.php file.

tllewellyn
  • 903
  • 2
  • 7
  • 28
  • Yes your right, I originally echoed out all the details from the previous form to ensure that they were being read correctly and all was good. Then I must have switched it to POST by accident. Now it's throwing me back a new error. 1064 for mysql. Will add the new error to OP! Thanks – Brad Andrews Aug 31 '15 at 00:04
  • Any time, good luck. – tllewellyn Aug 31 '15 at 00:05
0

Why are you putting all the information from the form in the link on submit? ex: account_create_submit.php?username=myusername&password=mypassword&isadmin=0


I can see that $username = $_POST['username']; doesn't match the username in your query string.

$query = "INSERT INTOusers(user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";

While your fixing that why don't you just make $isadminB and $_POST['isadmin'] the same. Use 'isadminB' in both places.

Check that out and see what happens!

benlevywebdesign
  • 339
  • 3
  • 13
  • Thanks, @Benlevywebdesign however the $username = $_POST['username']; is taking the previously submitted data from a form on the last page and storing it into the $username variable. The query then takes that data and is supposed to store it into the database. The user_name is the column name INSIDE my mysql database. Not the name of the field on the form on the previous page? – Brad Andrews Aug 30 '15 at 23:35
  • @BradAndrews Whats your submit button look like from the previous page? – benlevywebdesign Aug 30 '15 at 23:41
  • Username:

    Password:

    Is Admin: Yes | No
    – Brad Andrews Aug 30 '15 at 23:50
  • `try this` = code in between ` ` marks but put it in your question not here. – benlevywebdesign Aug 30 '15 at 23:52
0

password is a special word in MySQL, and it might be necessary to put the word in quotes like `password`.

Hkan
  • 3,243
  • 2
  • 22
  • 27
  • that's only if it's used as a function, which it is not. Do you see an `(R)` next to it https://dev.mysql.com/doc/refman/5.5/en/keywords.html – Funk Forty Niner Aug 31 '15 at 00:49