If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.
Related
Data is not inserted in sql
When the password are not equal password are not equal is working. However when the password match no data is being updated in my sql.
Had already tried to import data to sql directly from the database and also confirmed that connection to the database is done.
<?php
$host= 'localhost';
$user= 'root';
$pass= '';
$db= 'newusers';
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$con=mysqli_connect($host,$user,$pass,$db);
if($con)
/*echo 'Connected Successfully to newusers database';*/
//if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check passwords are equal
if($_POST['password'] != $_POST['confirmpassword']){
echo 'Passwords are not equal';
}
if ($_POST['password'] == $_POST['confirmpassword']){
$sql = "INSERT INTO signup (Name, Surname, Email, Password) values ('$name', '$surname', '$email', '$password')";
}
?>
The expected result is that if the passwords are equal the data will be uploaded to mysql
You have several problems with your code. First, you do not have curly brackets in the right places to make sure your comparisons are in context. You should have curly brackets surrounding your connect check:
if($con) {
// your code here
}
Fixing that, you then need to execute your query. One way of doing it is with mysqli_query():
$host= 'localhost';
$user= 'root';
$pass= '';
$db= 'newusers';
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$con=mysqli_connect($host,$user,$pass,$db);
if($con) { // added opening bracket here
/*echo 'Connected Successfully to newusers database';*/
//if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check passwords are equal
//} added closing bracket here
if($_POST['password'] != $_POST['confirmpassword']){
echo 'Passwords are not equal';
} else { // you don't need another 'if' statement
$sql = "INSERT INTO signup (Name, Surname, Email, Password) values ('$name', '$surname', '$email', '$password')";
$result = mysqli_query($con, $sql); // execute the query
}
}
WARNING!
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
Always check for errors!
Add error reporting to the top of your file(s) right after your opening <?php tag error_reporting(E_ALL); ini_set('display_errors', 1);
Add error checking, such as or die(mysqli_error($con)) to your queries. Or you can find the issues in your current error logs.
The form sends the data to this page. The print_r outputs everything I want to put into the table onscreen to check it's there, but nothing goes to the table. I have only managed to populate the table manually in phpmyadmin. Iam sorry if it's a really easy fix - I have only been learning for two weeks!
There are no errors showing in the logs or on screen when I run the page. The print_r does echo the array as it should be but nothing appears in the table
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'users';
$username = ($_POST['username']);
$password = ($_POST['password']);
$companyName = ($_POST['companyName']);
$confirmPassword = ($_POST['confirmPassword']);
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (mysqli_connect_errno()) {
// If there is an error with the connection, stop the script and
display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
print_r ($_POST);
// Now we check if the data was submitted, isset() function will check
//if the data exists.
if (!isset($_POST['username'], $_POST['password'],
$_POST['companyName'])) {
// Could not get the data that should have been sent.
die ('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) ||
empty($_POST['companyName'])) {
// One or more values are empty.
die ('Please complete the registration form');
}
print_r ($_POST);
// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM phplogin WHERE
username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the
//password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the
// database.
if ($stmt->num_rows > 0) {
// Username already exists
echo 'Username exists, please choose another!';
} else {
// Username doesnt exists, insert new account
/* $stmt = $con->prepare('INSERT INTO phplogin (username, password,
companyName ) VALUES (?, ?, ?)');*/
if (false !== true){
/* We do not want to expose passwords in our database, so hash the
password and use password_verify when a user logs in.
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['$username'], $password,
$_POST['$companyName']);
$stmt->execute();*/
$sql = 'INSERT INTO phplogin (username, password, companyName )
VALUES ($username, $password, $companyName)';
echo 'You have successfully registered, you can now login!';
echo (" ".$password." ".$username." ".$companyName);
echo ' well done';
} else {
/* Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.*/
echo 'Could not prepare the new statement!';
print_r ($_POST);
}
}
}
$con->close();
?>
//$sql = 'INSERT INTO phplogin (username, password, companyName ) VALUES ($_POST[username], $password, $_POST[companyName])';
PHP thinks it should execute VALUES even though it is not any proper action. Use /* THIS IS COMMENT */ because it prevents stuff like this happening.
Also as a side note: Do not assign values in if statement. You can assign $stmt on its own line and just check
If($stmt === true) {}
Or
If($stmt !== true) {}
You get the point.
Also another side note is that you should prefer using PDO. It is alot of easier to handle and understand because of ts syntax and it makes OOP much much more easier. Mysqli is ok to use, but i personally do not recommend using it.
I have a website that I need users to be able to login to. It is currently on a different server from the company's actual website. I would like to have a single login form that checks for a username and password in multiple databases on the same server.
Heres the setup.
1 Database has 2 different tables that I need to check for username and password.
the other database has 1 table that I need to check.
I will have a checkbox for 1 of the tables in the first database. So the form will have 3 field. (Username, Password, and "I am a reporter" checkbox)
I believe that it has something to do with the UNION sql command.
I don't know a LOT about sql but I am trying to learn as I go...
Here is the code so far.. also, I hope someone will tell me whether the information will be passed securely or not.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['pswd'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$uname=$_POST['uname'];
$pswd=$_POST['pswd'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from dbo.contacts where WebPwd='$password' AND WebAcctName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: "); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
It is not all complete yet and I am still researching but I am also trying to do this as quick as possible.
any help will be greatly appreciated!
It appears you make a connection declaring one name and then a different connection object name later.
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
$db = mysql_select_db("company", $connection);
I believe the later should use the same name $con and also at the end mysql_close($con);
First, you should use the mysqli_ or PDO API instead of mysql statements
If you need to use mysql, here is what to do:
$QueryReporter = mysql_query("SELECT * FROM $ReporterTable WHERE Username = '$Username' AND Password = '$Password'");
$QueryOthers = mysql_query("SELECT * FROM $UserTable WHERE Username ='$Username' AND Password = '$Password'");
if(mysql_num_rows($QueryReporter)==1){
//Its a reporter
}
else if(mysql_num_rows($QueryOthers)==1){
//Its not a reporter, but a user
}
else{
//Its no user or reporter, show error :)
}
EDIT:
If you are thinking about two different DB servers, you can use a function, then close the connection after the full query and return the result:
function CheckIfReporter($Username, $Password){
//DATABASE CONNECTION TO REPORTER DB
$Query = mysql_query("SELECT * FROM MyTable WHERE Username = '$Username' AND Password = '$Password'");
if(mysql_num_rows($Query)==1){
return TRUE;
}
//Else, no result:
else{
return FALSE;
}
//Close mysqlconnection:
mysql_close();
}
Now, make a similar function for user check,
if(CheckIfReporter($UsernameInput, $PasswordInput)==TRUE){
//Its a reporter
}
else if(CheckIfUser($UsernameInput, $PasswordInput)==TRUE){
//Its a user
}
else{
//Its none
}
I'm trying to display a message upon a successful user registration however what I have doesn't seem to be working and just submits/refreshes the page. No message pops up even though data has successful been entered into the SQL database. Any tips or ideas?
<?php
require('php/connect.php');
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, password, email) VALUES ('$username', '$password', '$email')";
$result = mysql_query($query);
if($result){
echo $msg = "Successful Registration!";
}
}
?>
Learning PHP currently so sorry if there's a really obvious answer here!
Edit: Forgot to include echo. Just needed a second pair of eyes, sorry guys. Thanks for the tips!
First of all have this on consideration:
If you're getting started on PHP, please stop using mysql. It's deprecated, instead, you can use either PDO or MySQLi
As for your issue, your message is not being printed. Please make sure you echo the $msg variable:
$msg = "Successful Registration!";
echo $msg;
In mysqli a standard connection would be:
$DBConnect = new mysqli('serverName', 'userName', 'userPassword', 'dbName');
And that's it, that's all you need to start querying your database using mysqli.
For a mysql connection, try debugging it, see if there's a connection:
$connection = mysql_connect('localhost', 'userName', 'userPassword');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
Try to echo message
if($result)
{
echo $msg = "Successful Registration!";
}
<?php
echo "Successfully registered!";
?>
I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.