Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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());
}
share|improve this question

closed as off-topic by Fred -ii-, andrewsi, Shankar Damodaran, Abdulla, Marcus Aug 31 at 4:41

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting." – Fred -ii-, Shankar Damodaran, Abdulla, Marcus
If this question can be reworded to fit the rules in the help center, please edit the question.

2  
Do yourself a favor and migrate to PDO instead of using deprecated mysql_* functions. – Charlotte Dunois Aug 30 at 20:36
1  
what she said ↑ – Drew Aug 30 at 20:39
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 at 21:57
2  
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 at 23:46
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 at 0:18

4 Answers 4

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!

share|improve this answer
    
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 at 23:35
    
@BradAndrews Whats your submit button look like from the previous page? – benlevywebdesign Aug 30 at 23:41
    
<pre><form action="account_create_submit.php" method="get"> 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><pre> – Brad Andrews Aug 30 at 23:50
    
try this = code in between ` ` marks but put it in your question not here. – benlevywebdesign Aug 30 at 23:52

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

share|improve this answer
    
that's only if it's used as a function, which it is not. Do you see an (R) next to it dev.mysql.com/doc/refman/5.5/en/keywords.html – Fred -ii- Aug 31 at 0:49

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.

share|improve this answer
    
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 at 0:04
    
Any time, good luck. – tllewellyn Aug 31 at 0:05

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
}
share|improve this answer
    
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 at 0:26
1  
Fred -ii-, I'll re-upvote your answers if you do mine. Cheers – tllewellyn Aug 31 at 0:51
1  
@tllewellyn Yeah, some fu**ing bozo who knows shit about the word password dev.mysql.com/doc/refman/5.5/en/keywords.html – Fred -ii- Aug 31 at 0:51
1  
The amount of time spent trying to help out the OP... whoever it was is a j@ck***. – tllewellyn Aug 31 at 0: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! – user5173426 Sep 2 at 17:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.