mysql query insert error - mysql

The INSERT into staffprofiles mysql query (near the bottom of the code) is getting the "or die" statement triggered. Can anyone see why? The first one into staffusers is fine. Am I breaking a rule by having 2 insert commands or something? If so, is there another way to code what I am trying to do? Thank you in advance for any help.
Also, I will be address SQL injection and other items shortly. I just want to get this figured out first. Thanks.
<html>
<head>
<title>XXXXXXX</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="back">
</div>
<div id="wrapper">
<div id="header">
<div id="logout">
<?php
include 'header.php';
?>
</div>
<span><b>XXXXXXX</b>XXXXXX</span>
</div>
<?php
include 'menu.php';
if (isset ($_POST['submit']))
{
}
else
{
echo "not set";
}
$user=$_POST['username'];
$pass1=$_POST['pass1'];
$pass2=$_POST['pass2'];
$email=$_POST['email'];
$user=strip_tags($user);
$email=strip_tags($email);
$pass1=strip_tags($pass1);
$isemail = "SELECT * from staffusers where email ='$email'";
$isemail2 = mysql_query($isemail) or die ("could not query email in table");
$isemail3 = mysql_fetch_array($isemail2);
if ($isemail3)
{
echo "That email address is already registered.<br>";
echo "<a href='forgotpassword.php'>Forgot passsword.</a><br>";
echo "<a href='staffregisterform.php'>Go back to register under a different email address.</a>";
exit;
}
if ($email == "" || $user == "" || $pass1 == "" || $pass2 == "")
{
echo "please complete all fields before submitting<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
if (strlen($pass1)<6)
{
echo "Your password must be at least 6 characters in length.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
if ($pass1 == $pass2)
{
$isplayer = "SELECT * from staffusers where username ='$user'";
$isplayer2 = mysql_query($isplayer) or die ("could not query user in table");
$isplayer3 = mysql_fetch_array($isplayer2);
if ($isplayer3)
{
echo "The username ''$user'' is already taken. Please try another username.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
if (strlen($user)>16 || strlen($user)<2)
{
echo "Your username must be be at 2 two characters and at most, 16 characters.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
}
else
{
echo "The passwords do not match.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
$pass1=MD5($pass1);
$register = "INSERT INTO staffusers (username, password, email) VALUES ('$user', '$pass1', '$email')";
mysql_query($register) or die ("staffusers.");
$profile = "INSERT INTO staffprofiles (username, email) VALUES ('$user', '$email')";
mysql_query($profile) or die ("staffprofiles.");
echo "Thank you for registering, $user.<br>";
echo "<a href='index.php'>Login</a>";
?>

If you have valid fieldnames and table names then try;
$profile = mysql_query("INSERT INTO staffprofiles (username, email) VALUES ('$user', '$email')");
// use some value directly to check as:
$user = "Tester";
$email= "something#test.com";
$profile = mysql_query("INSERT INTO staffprofiles (username, email) VALUES ('$user', '$email')");
//if this value gets inserted then you have problem in $user variables value
Hope it helps

Related

Getting data from database using part of the URL as a value - PHP

My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.

Connecting mySQL db through PHP

Let me begin by saying I am extremely new at this. I am trying to develop a mobile app and a website with no real experience. There is likely something that I have missed or I am doing wrong but I cannot seem to pin point where the issue is. Prior to creating my own, I followed a video guide (with the demo files downloaded to my computer) but cannot seem to connect to my database. I have also copied the demo files and placed them into my code and it is still getting me caught on one section. I am using the program MAMP for the connection and Brackets for the code. Below are my session files:
Database connection-
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "Login System";
$con = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
My sign up document-
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
echo <h2>Please fill in all fields;
exit ();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO users (first, last, email, uid, pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
?>
My Login Sheet
<?php
include_once 'header.php';
?>
<section class="main-container">
<div class="main-wrapper">
<h2>Signup</h2>
<form class="signup-form" action="includes/signup.inc.php" method="POST">
<input type="text" name="first" placeholder="Firstname">
<input type="text" name="last" placeholder="Lastname">
<input type="text" name="email" placeholder="E-mail">
<input type="text" name="uid" placeholder="Username">
<input type="password" name="pwd" placeholder="Password">
<Button type="submit" name="submit">Sign up</Button>
</form>
</div>
</section>
<?php
include_once 'footer.php';
?>
I have reset the password for 'root' to 'root' and ensured I can login with that. The document that checks for error's lists if any field is empty, return to the previous page with the word "=empty" in the url. No matter what I type into my fields, it is either not pushing the information into the database or I have incorrectly mapped my fields so one of the database fields is empty.
Any help would be greatly appreciated. As I said at the beginning of this post, I am extremely new at this. You may see something that is incredibly obvious and somewhat dumb... you've been warned! I am working on creating a mobile application and website that allows users to login. The login attempt will reference my localhost database to confirm that the user does not exist or that the user is not in use.
Thank you!
To check the connection handling, you can add this after the connect attempt:
$conn = mysqli_connect( ... );
if ( !$conn ) {
die( 'Did not connect: ' . mysqli_connect_error() );
}
To check the handling after a query, you can add this after the query attempt:
$result = mysqli_query( $conn, $sql );
if (false === $result) {
die( 'Query error: ' . mysqli_error($conn) );
}
Using php -l right off the bat I found some errors in your code in the includes/signup.inc.php file.
The line echo <h2>Please fill in all fields; was not quoted which would cause an error 500 when I tried to load the page. To fix this I added single quotes echo '<h2>Please fill in all fields</h2>'; and added </h2> to close the HTML tag.
After that was fixed the page would return Please fill in all fields even though I had filled all the fields in the sign up form. to fix this issue I changed mysqli_real_escape_string($conn, $_POST['POST_DATA']); to strip_tags(trim($_POST['POST_DATA']));.
The email line is a little bit different, mysqli_real_escape_string($conn, $_POST['email']); is changed to filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
I also changed the $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT); (PHP Documentation: http://php.net/manual/en/function.password-hash.php) line to add salt. What is salt?
In cryptography, a salt is random data that is used as an additional
input to a one-way function that "hashes" a password or passphrase.
Salts are closely related to the concept of nonce. The primary
function of salts is to defend against dictionary attacks or against
its hashed equivalent, a pre-computed rainbow table attack.
Source: en.wikipedia.org/wiki/Salt_(cryptography)
Also take a look at this post in stackexchange/security for some more information Link: https://security.stackexchange.com/a/51983
New includes/signup.inc.php file
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = strip_tags(trim($_POST['first']));
$last = strip_tags(trim($_POST['last']));
$email = filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
$uid = strip_tags(trim($_POST['uid']));
$pwd = strip_tags(trim($_POST['pwd']));
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
echo '<h2>Please fill in all fields</h2>'; // was echo <h2>Please fill in all fields; which would cause an error 500
exit ();
}
else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
}
else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
}
else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
}
else {
//Hashing the password
$options = [
'cost' => 12,
];
$hashedPwd = password_hash($password, PASSWORD_BCRYPT, $options); // Adding salt to hashed password
//Insert the user into the database
$sql = "
INSERT INTO users (first, last, email, uid, pwd)
VALUES ('" . $first . "',
'" . $last . "',
'" . $email . "',
'" . $uid . "',
'" . $hashedPwd . "');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
}
else {
header("Location: ../signup.php");
exit();
}
?>
In addition it would be a good idea to learn how to use the OOP style of mysqli to do more complex database manipulation
PHP Documentation on mysqli: php.net/manual/en/mysqli.query.php
It would also be good to add a column to act as a serial number to allow later editing of values for the users using this MySQL Query:
ALTER TABLE `users` ADD `serial` INT PRIMARY KEY AUTO_INCREMENT;

Saving Each Token in Separate row in Database

I am trying to save each string token in separate row in database, so that i can compare it with other string Tokens.
I am using PHP explode function and my syntax is:
<?php
$someWords = "Please don't, blow me to pieces.";
$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
echo "Piece $i = $wordChunks[$i] <br />";
$con = mysqli_connect("localhost","","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO TableName (file1) VALUES ('$wordChunks')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully";
mysqli_close($con);
}
?>
It gives this output
And i want this output
[
Use the MySQL mysqli_real_escape_string function to escape the string before including it in the query:
$sql = 'INSERT INTO TableName (file1) VALUES ('.mysqli_real_escape_string($wordChunks[$i]).')';

Unable to Change Password Correctly

As much as I've tried I can't see why this code wouldn't work. Whenever I atmempt to change a password using this page, it says an incorrect password has been supplied.
This is the last page I have to get to work for this site, so any help would be appreciated.
<?php
require_once ("dbconnect.php");
// include file to do db connect
require_once ('checklog.php');
require_once ("functions.php");
session_start();
$username = ($_POST['username']);
$password = ($_POST['password']);
$newpassword = ($_POST['newpassword']);
$repeatpassword = ($_POST['repeatpassword']);
if (isset($_POST['submit'])) {
if ($username && $password) {
$hashpass = salt($password);
$query = "SELECT ID FROM users WHERE username='$username' AND password='$hashpass'";
if ($username == $datausername && salt($password) == $datapassword) {
// PASSWORD CHANGING IS DONE HERE
if ($newpassword == $repeatpassword) {
// From register
if (strlen($newpassword) > 25 || strlen($newpassword) < 6) {
$message = "Password must be 6-25 characters long";
}
else {
// part 8
// Process details here
if ($db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}
else {
if ($db_server) {
// clean the input now that we have a db connection
$newpassword = clean_string($db_server, $newpassword);
$repeatpassword = clean_string($db_server, $repeatpassword);
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)) {
$message = "This is your current password. Please try again.";
}
else {
// Process further here
$newpassword = salt($newpassword);
$query = "UPDATE INTO users (password) VALUES ('$password')";
mysqli_query($db_server, $query) or die("Insert failed. " . mysqli_error($db_server));
$message = "<h1>Your password has been changed!</h1>";
}
mysqli_free_result($result);
}
else {
$message = "Error: could not connect to the database.";
}
mysqli_close($db_server);
// include file to do db close
}
}
// This code appears if passwords dont match
}
else {
$message = "<h1>Your new passwords do not match! Try again.</h1>";
}
}
else {
$message = "<h1>Incorrect password!</h1>";
}
}
else {
$message = "<h1>That user does not exist!</h1>" . "Please <a href='password.php'>try again</a>";
}
// Close connection!
}
else {
$message = "<h1>Please enter a valid username/password</h1>";
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<?php
include_once ("header.php");
?>
<div id="apDiv1"><span class="rich-list">
<title>Change your Password</title>
<h1>So you want to change your password, <?php
echo $_SESSION['username'];
?>?</h1>
<form action='password.php' method='POST'>
<div align="right">Current Username:
<input type='text' name='username'><br />
Current Password: <input type='password' name='password'><br />
New Password: <input type='password' name='newpassword'><br />
Repeat New Password: <input type='password' name='repeatpassword'><br />
<input type='submit' name='submit' value='Confirm'>
<input name='reset' type='reset' value='Reset'>
</div>
</form>
<?php
echo $message
?>
<?php
include_once ("footer.php");
?>
</div>
</body>
</html>
</body>
</html>
I don't know how the 'salt' function is defined - you might want to include it in your post.
I suspect that salt will pick some random salt, and hash with that - if so, to verify, you will need to use the salt from the encrypted password, or you will get a different outcome.
So, to verify a password:
get the username and guess,
get the encrypted password for the username
get the salt from the encrypted password (often the first few characters)
encrypt the guess with the salt from the encrypted password
compare this encrypted guess to the encrypted password.
Ignoring the many bad practices in your code for now, the problem is that you never retrieve the user's password from the database:
// $datausername and $datapassword have not been set, so this will always be false
if ($username == $datausername && salt($password) == $datapassword) {
// ... code
} else {
$message = "<h1>Incorrect password!</h1>";
}
You did set the $query string, but you forgot to run the actual query in the database and retrieve the results, if any.
To run a query, first you establish a database connection:
$dbc = new mysqli("db_host", "db_user", "db_password", "db_name");
if (mysqli_connect_errno()) {
die("Could not connect to MySQL: " . mysqli_connect_error());
}
Let's assume you did that in your "dbconnect.php" file, so now you have a valid $dbc connection and your $query string. The following will give you a mysqli_result object, or FALSE if the query fails.
$result = $dbc->query($query);
Please see the PHP manual for more information on how to use that object.
Also, PHP has an excellent built-in function called password_hash - I suggest you use this instead of what appears to be a custom-defined function 'salt'.
To further improve your code, you should learn about SQL Injection and how to avoid it, such as by using prepared statements.

$_POST leads to empty fields in MySQL Database

Thank you for taking the time to read this. This question may or may not have been answered before, I might have been looking in the wrong place, but I've hit a dead end wall here and I hope I could ask for some help finding a solution.
I'm using a basic form with a validation for specific fields and checkboxes before I'm sending them in a query to my database.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// validate the text inputs
$err = array();
if (empty($_POST['A'])) {
array_push($err, "A is required.");
}
if (empty($_POST['B'])) {
array_push($err, "B is required.");
}
if (empty($_POST['C'])) {
array_push($err, "C is required.");
} else {
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (!eregi($pattern, $_POST['email'])) {
array_push($err, "Incorrect email.");
}
}
if (empty($_POST['D'])) {
array_push($err, "D is required.");
if (sizeof($err) != 0) {
echo "<p style='color: red'>The following files haven't been filled yet.</p>";
echo "<ul style='list-style:circle !important;color: red !important;'>";
foreach ($err as &$value) {
echo "<li style='background: 0;list-style: disc inside none;color: red;'>" . $value . "</li>";
}
echo "</ul>";
echo "<br/>";
}
// validate the agree checkbox
if (sizeof($err) == 0 && !isset($_POST['agree'])) {
array_push($err, "Please agree with the ToS.");
foreach ($err as &$value) {
echo "<p style='color: red'>" . $value . "</p>";
}
}
}
?>
Then the inside the form we got this:
<?php echo isset($_POST['a']) ? $_POST['a'] : ''; ?>"
The other lines are the same, so I'll save you from having to read a huge block. From there on I sent the code towards:
<?php
// redirect if form is valid
if (sizeof($err) == 0 && isset($_POST['agree'])) {
// set post data in session
session_start();
$_POST = $_SESSION['POSTDATA'];
$con = mysqli_connect("localhost", "x", "y", "z");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO esselte_nl (a, b, email, c, d) VALUES
('$_POST[a]',
'$_POST[b]',
'$_POST[email]',
'$_POST[c]',
'$_POST[d]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
// redirect to result.php
exit('<meta http-equiv="refresh" content="0; url=resullt"/>');
return;
session_destroy();
}
?>
Worst thing is, I'm fairly certain it's some very small error somewhere and I'm overlooking it, terribly frustrating. So if anyone could potentially point out whatever I'm doing wrong here, I'd appreciate it.
With friendly regards,
user2747008 (I really should pick a name though)
PS: Sorry about that, I messed up copying pasting the information.
$sql = "INSERT INTO esselte_nl (a, b, email, c, d) VALUES
('$_POST[a]',
'$_POST[b]',
'$_POST[c]',
'$_POST[email]')";
Your insert statement has 5 field names, but only 4 values, and they aren't in the correct order.