mysql UPDATE not changing table - php

I have a made a form to allow for changing a users "UserLevel." However, I cannot seem to get it to work. It just is not changing the UserLevel after submit. I am definitely a PHP newbie. But I have tried researching this for the past hour and cannot seem to make any progress here. Probably something simple I am missing. Any help is appreciated.
The form
<form action="dm/userUpdate.php" method="post">
Username: <input type="text" name="username" value="Username">
<br>
User Level: <input type="number" name="userlevel" value="0">
<input type="Submit" name="submit" value="Change">
</form>
userUpdate.php
<?php
mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$userlevel = mysql_real_escape_string($_POST["userlevel"]);
$username = mysql_real_escape_string($_POST["username"]);
mysql_query($con,"UPDATE users SET UserLevel= $userlevel WHERE Username ='$username'");
mysql_close($con);
?>

You should escape your variables. Or whatever this is called.
mysql_query("UPDATE users SET UserLevel= '".$userlevel."' WHERE Username ='".$username."'");
Notice i used regular MySQL so no link is required as a parameter. If you are new to MySQL i advice to learn MySQLi right off the bat since it has some handy improvements.

You can't mix mysqli (note the I) and mysql (without an i) functions. The two libraries are NOT interchangeable.
As well, your SQL itself has syntax errors - mysql_real_escape_string() does NOT quote strings for you - it only escapes sql metacharacters, so you'll end up something like
... WHERE Username = Miles O\'Brien
instead of
... WHERE Username = 'Miles O\'Brien'

try this
mysql_query("UPDATE users SET UserLevel= '$userlevel' WHERE Username ='$username'");
mysql_close();
you have no $con variable defined.

Always check for syntax errors. Look at your table name and table fields and make sure they are spelled the same as well as cased.

<?php
$con = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db("database", $con) or die(mysql_error());
$userlevel = mysql_real_escape_string($_POST["userlevel"], $con);
$username = mysql_real_escape_string($_POST["username"], $con);
mysql_query("UPDATE users SET UserLevel= " . $userlevel . " WHERE Username ='" . $username . "'", $con);
mysql_close($con);
?>
use $con to hold connection link on connected data base and use mysql_query (not mysqli_query it is for MySQLi) and other functtions with that connection variable to work with connected database!

Related

MySQL error code 0 in PHP? Cannot insert data into database with PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
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());
}
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.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
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
}
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.
password is a special word in MySQL, and it might be necessary to put the word in quotes like `password`.
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!

How to insert long Strings into mySQL database using PHP?

I'm using a simple html-form and PHP to insert Strings into mySQL Database, which works fine for short strings, not for long ones indeed.
Using the phpmyadmin I'm able to insert Strings of all lengths, it's only doesn't work with the html file and PHP.
Will appreciate every kind of help, would love to learn more about this topic...
Thank you all a lot in advance and sorry if the question is to simple...
There are two very similar questions, I found so far... unfortunately they couldn't help:
INSERTing very long string in an SQL query - ERROR
How to insert long text in Mysql database ("Text" Datatype) using PHP
Here you can find my html-form:
<html>
<body>
<form name="input" action = "uploadDataANDGetID.php" method="post">
What is your Name? <input type="text" name="Name"><br>
Special about you? <input type="text" name="ThatsMe"><br>
<input type ="submit" value="Und ab die Post!">
</form>
</body>
</html>
and here is the PHP-Script named uploadDataANDGetID.php :
<?php
$name = $_POST["Name"];
$text = $_POST["ThatsMe"];
$con = mysql_connect("localhost", "username", "password") or die("No connection established.");
mysql_select_db("db_name") or die("Database wasn't found");
$q_post = mysql_query("INSERT INTO profiles VALUES (null, '{$name}' ,'{$text}')");
$q_getID =mysql_query("SELECT ID FROM profiles WHERE Name = '{$name}' AND ThatsMe = '{$text}'");
if(!$q_post) // if INSERT wasn't successful...
{
print('[{"ID": "-3"}]');
print("uploadDataAndGetID: Insert wasn't successful...");
print("about ME: ".$text);
}
else // insertion succeeded
{
while ($e=mysql_fetch_assoc($q_getID))
$output[]=$e;
//checking whether SELECTion succeeded too...
$num_results = mysql_num_rows($q_getID);
if($num_results < 1)
{
// no such profile available
print('[{"ID": "-1"}]');
}
else
{
print(json_encode($output));
}
}
mysql_close();
?>
Thank you guys!
Use the newer way to connect to MySQL and use prepared statements http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
you MUST escape your strings, with mysql_real_escape_string, like this:
$name = mysql_real_escape_string($_POST['Name']);
$text = mysql_real_escape_string($_POST["ThatsMe"]);
$q_post = mysql_query('INSERT INTO profiles VALUES (null, "' . $name . '" ,"' . $text . '")');
also read about SQL injection

MySQL form on MAMP not working properly

The problem is I simply want to insert the fullname/address. I created a users table with the following columns: id (primary), fullname (unique), address (unique).
Here's the code:
<?php $username = "root";
$password = "artislife23";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select examples");?>
<body>
<div class="container">
<div class="content">
<h1><?php if(($selected!=null)){
echo "Database is on lock.";}
if(($dbhandle!=null)){
echo "Connected to MySQL<br>";
}?></h1>
<form method="post" action="input.php">
<tr><td>Name</td><td><input type="text" name="fullname" size="20"></td></tr>
<tr><td>Address</td><td><input type="text" name="address" size="40"></td></tr>
<tr><td></td><td align="right"><input type="submit" value="Submit"></td>
Here's input.php
<?php
$postr="INSERT INTO users
(fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
$result = mysql_query($postr);
echo "$result";?>
All that I can see that's happening is a single blank entry was inserted into the table. Am I doing something wrong here? All I want is to successfully insert the form data into my users table here.
$_POST['fullname']
you are missing quotes in your POSTs.
The reason why it doesn't work is that PHP doesn't expand arrays in strings the same way it does variables without some weird syntax I can never remember. Change:
$postr="INSERT INTO users (fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
To:
$postr="INSERT INTO users (fullname, address) VALUES('".$_POST['fullname']."','".$_POST['address']."')";
You were also missing the quotes on the array keys.
Additional notes:
Your code is wide open to SQL injection, if I entered my name as Bobby'; DROP TABLE users;-- guess what would happen?
mysql_*() functions are deprecated, take the time to learn PDO or MySQLi. They have neat thigns called 'parameterized queries' that allow you to easily avoid SQL injection like I've noted above.
Assuming that either a person's full name or address to be unique to them is a design mistake, don't do this in a 'real-world' project.
Edit
Alternate syntax for embedding arrays in strings:
$string = "Fee fie {$foo['bar']}.";

How do I complete this login script?

I've almost completed my login script, but I don't know how to check if the username & password is correct.
Here's my script files.
index.php:
<html>
<body>
<form action="action1.php" method="post">
Username: <input type="text" name="uname">
Password: <input type="password" name="pword">
<input type="submit">
</form>
</body>
</html>
The index.php file is just the page that I use to collect the info from my users for registration.
action1.php:
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die ('Could not connect: ' . mysql_error());
}
mysql_select_db("user1", $con);
$sql="INSERT INTO useri1 (uname, pword)
VALUES
('$_POST[uname]','$_POST[pword]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The action1.php file is just the page that registers the users into the database.
login.php:
<html>
<body>
<form action="checklogin.php" method="post">
Username: <input type="text" name="uname1">
Password: <input type="password" name="pword1">
<input type="submit">
</form>
</body>
</html>
The login.php file is just the page I use for the users to type their login info in.
Now this is my problem, I have no idea of how to check the users login info so they can proceed to the members only area. I'm a newbie & any help is GREATLY appreciated.
Thanks,
--Devin
Firstly you want to use mysqli instead of mysql, because mysql is outdated and no longer actively developed. Secondly you want to start escaping your database queries to stop sql injection. In the code below, I used a session to keep track of the user. You can learn more about sessions here.
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'user1');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$userName = $mysqli->real_escape_string($_POST['uname1']);
/* query database */
$result = $mysqli->query("SELECT `pword` FROM `user1` WHERE `uname` = '".$userName."'");
if ($result->num_rows == 1) {
while ($col = $result->fetch_array(MYSQLI_ASSOC)) {
// This presumes you're storing your passwords in plain text.
// If you hashed your passwords or anything, you would have to do the same to $_POST['pword']
if ($_POST['pword'] == $col['pword']) {
// You could do anything here, but sessions are a way of keeping track of a user.
$_SESSION['userName'] = $_POST['uname1'];
$_SESSION['loggedIn'] = true;
}
}
}
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
You would run a query along the lines of this:
$user_check_query = "SELECT * FROM useri1 WHERE uname=" . $_POST['uname'] . " AND pword=" . $_POST['pword'] .";";
And if the query returns a value, then they can proceed. If the query returns nothing, they cannot pass. As for the logic, look at the code you have created and see how to create if and else statements to handle the logic.
You need to do a SELECT query - something along the lines of
SELECT STRCMP('{$_POST['pword']}', pword) FROM useri1 WHERE uname = '{$_POST['uname']}'
This should return a value in the range [-1, 1] - if it is not 0, the password is wrong. If there is no rows, the user does not exist.
You need to think about SQL injections as well - but that could very well be an exercise for another day.

Jquery/PHP ajax login system

I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?

Categories