Specifying parameters for a PHP sql query - php

I want to specify a raw username/password into an SQL query with PHP:
function doRegister($username, $password) {
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die('error');
$query = "SELECT username FROM users WHERE username = $username";
$result = $db->query($query);
if (mysqli_num_rows($result) == 1) {
$msg = 'Username already taken';
} else {
$register = "INSERT INTO users(username, password)" .
"VALUES($username, SHA($password))";
//error happens here
$db->query($register) or die('error registering your account');
$msg = "Register successful";
}
$db->close();
echo $msg;
}
I am getting an error at $db->query($register). What am I doing wrong?

You have not surrounded your $username or $password in quotes, so when passing an integer it works correctly but won't accept a string:
$query = "SELECT username FROM users WHERE username = '$username'";
//----------------------------------------------------^^^^^^^^^^^^
$register = "INSERT INTO users(username, password)" .
"VALUES('$username', SHA('$password'))";
//-------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Please be certain that you have properly escaped these values with mysql_real_escape_string().
These columns should really not be type TEXT. They ought to be VARCHAR(). Perhaps your VARCHAR() attempt failed because you were missing the length parameter, as in VARCHAR(32) for max 32 characters.

Try this:
function doRegister($username, $password) {
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die('error');
$query = "SELECT username FROM users WHERE username = '$username'";
$result = $db->query($query);
if (mysqli_num_rows($result) == 1) {
$msg = 'Username already taken';
} else {
$register = "INSERT INTO users(username, password)" .
"VALUES('$username', SHA('$password'))";
$db->query($register) or die('error registering your account');
$msg = "Register successful";
}
$db->close();
echo $msg;
}

Related

I can't connect my database table to my website in order to register and sign in

My website fully functions on localhost but now that I put it on web hosting the account doesn't work, I cannot register or login. I know that it works because it previously did so there is a problem with the connection to the user table in my database. The other table with products is successfully connected. How do I fix this problem in my code?
<?php
include ('connect.php');
$conn = connect();
$email = $_POST['Email'];
$pass = $_POST['Password'];
$type = $_POST['type'];
if($type == "signup"){
$sql = $conn->prepare("SELECT * FROM user WHERE Email like ?");
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
echo "This email is already in use";
}
else{
/*Part 1*/
$sqlInsert = $conn->prepare("INSERT INTO `user` (`UID`, `Email`, `Password`, `FName`, `LName`, `Country`, `City`, `Address`) VALUES (NULL, ?, ?, '', '', '', '', '');");
$sqlInsert->bind_param('ss', $email, $pass);
$sqlInsert->execute();
echo "Success!";
}
}
else if($type == "login"){
$sql = $conn->prepare("SELECT * FROM user WHERE Email like ?");
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
if($row["Password"] == $pass){
// Log in
session_start();
$_SESSION['login_user'] = $email;
$_SESSION['account_id'] = $row["UID"];
echo "Success!";
}
else{
echo "Wrong credentials!";
}
}
}
else{
echo "Wrong credentials!";
}
}
mysqli_close($conn);
?>
I think the problem may be here
<?php
include 'config.php';
function connect() {
$conn = new mysqli(SERVER_NAME, USER, PASSWORD, DB_NAME);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
return $conn;
}
?>
you can use this code please fill below fields
my_user: default 'root'
my_password: default ''
my_db: your database name
<?php
include 'config.php';
function connect()
{
$con = mysqli_connect("localhost", "root", "", "my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $con;
}
?>

PHP is not passing proper data to MYSQL

I am unable to pass proper data to MySQL I have no idea what is wrong done by me please help me out my code is as follow:
$con = mysqli_connect('localhost', 'root', '', 'database');
if($con) {
echo "we are connected";
} else {
die("connection failed");
}
if(isset($_POST['submit'])) {
// echo "Yeah it works";
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "INSERT INTO users(username, password) VALUES ('$user', '$pass')";
$result = mysqli_query($con, $query);
if(!$result) {
die("Query failed");
}
}
When I run this code I'm getting 0 for username and 0 for password. whatever I type for username and password I get 0 in database.
Try this code, which also removes SQL injections.
$con = mysqli_connect('localhost', 'root', '', 'database');
if(! $con )
die('Unable to connect');
foreach(array('submit', 'username', 'password') as $arg)
if(! isset($_POST[$arg]) )
die('Missing argument(s)');
unset($arg);
http_response_code(200);
$username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string($_POST['password']);
$query = "INSERT INTO users (username, password) VALUES ('{$username}', '{$password}')";
if(! mysqli_query($con, $query))
http_response_code(400);
If this code doesn't work, make sure that username and password from your table are varchar's not int's. (Because your script inserts a 0 value)

Data is not inserting on the database Game resgistration

So im making a web game app my problem is my register.php is not inserting users in the database please need help by the way im just a beginner in PHP Thanks
Here is the Code:
<?php
require_once('mysql_conn.php');
$Username = mysql_real_escape_string($_POST['Username']);
$Password = md5(mysql_real_escape_string($_POST['Password']));
$Email = mysql_real_escape_string($_POST['Email']);
$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
$retval_check = mysql_query( $query_check, $conn );
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if(mysql_num_rows($retval_check)){
echo"Username Already Taken";
} else {
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
$retval = mysql_query( $query, $conn );
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
mysql_close($conn);
?>
Change:
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
To:
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
You forgot to add a comma ","
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
YOu miss the coma between user_pass and email in column name
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
try mysqli
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
//require_once('mysql_conn.php');
$Username = mysqli_real_escape_string($_POST['Username']);
$Password = md5(mysqli_real_escape_string($_POST['Password']));
$Email = mysqli_real_escape_string($_POST['Email']);
//$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
// $retval_check = mysqli_query( $query_check, $conn );
if(!empty($Username))
{
$stmt = $conn->prepare("SELECT user_name FROM account_info WHERE user_name =? ");
$stmt->bind_param('s',$Username);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
//$row_count= $stmt->affected_rows;
$stmt->close();
//$conn->close();
}
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if($row_count>0){
echo"Username Already Taken";
} else {
//$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
^^^^^
//$retval = mysql_query( $query, $conn );
$stmt1 = $conn->prepare("INSERT INTO account_info(user_name,user_pass,email) VALUES (?,?,?)");
$stmt->bind_param('sss',$Username,$Password,$Email);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt1->execute();
//$get_result1 =$stmt1->get_result();
//$row_count1= $get_result1->num_rows;
$row_count1= $stmt1->affected_rows;
$stmt1->close();
$conn->close();
if($row_count1>0)
{
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
}
else
{
echo "<script>";
echo "alert('registeration failed')";
echo "</script>";
}
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
wrong
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
correct
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email')";

Inserting data to mysql not working

<?
session_start();
if(($connection = mysql_connect("localhost", "root", "")) == false)
die ("Couldn't connect to database");
if(mysql_select_db("Social", $connection) == false)
die ("Couldn't select db");
if (isset($_POST['username']) && isset($_POST['pass']) && isset($_POST['login'])){
$sql = sprintf("SELECT * FROM users WHERE username LIKE '%s' AND password LIKE '%s'", $_POST['username'], $_POST['pass']);
$query = mysql_query($sql);
if (mysql_num_rows($query) == 0){
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['newUser'], $_POST['newPass']);
$query2 = mysql_query($sql2);
if (!$query2){
print "Registration failed";
}
else{
print "Registration sucessfull";
}
}
?>
My program is not inserting any data into mySQL table. I know all the syntax is right, everything should work out fine. I double checked on the command that mySQL uses in order to enter data into the table. Why is this not working? My query2 should be successful, but idk why its not.
Please help.
Thanks
to prevent sql injections, try mysqli or pdo
here is mysqli prepared statements version. However if you are trying to create user management system, I wouldn't recommend you do it. There are so many scripts which provide more security, http://www.usercake.com is a good user management system.
session_start();
$db = new mysqli('localhost', 'root', 'password', 'database');
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_POST['username'] && $_POST['pass'] && $_POST['login']))
{
$user_name = ''; //define these here.
$pass = '';
$stmt = $db->prepare("select * from users where username = ? and password = ?");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $user_name, $pass);
$stmt->execute();
$result = $stmt->get_result();//get rows
if($result->num_rows < 1) //check if result is less than 1
{
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$uname = $_POST['newUser'];
$pass = $_POST['newPass'];
if(empty($uname))
{
echo "Please enter your username.";
}
elseif(empty($pass))
{
echo "Please enter your password.";
}
else{
$stmt = $db->prepare("insert into Social.users (username, password) values (?,?)");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $uname, $pass);
$stmt->execute();
echo "You have successfully registered.";
}
}
The variables in the INSERT must be the username and password
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['username'], $_POST['pass']);
Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Using mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name =
?'); $stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result(); while ($row = $result->fetch_assoc()) {
// do something with $row }
Font: How can I prevent SQL injection in PHP?

Why won't the data be stored in my database?

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You might also want to rather make use of PDO then you don't have to to do the cleanup of the user input as PDO will take care of that for you. You might want to creat a file that hold all your connection details like this:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user authentication');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DSN', 'mysql:host='. DB_HOST . ';dbname=' . DB_NAME);
?>
You then might want to create a class to do the connection to your database like:
<?php
class database{
public function databaseConnect(){
/*Creates a new instance of the PDO called $db.
* NOTE: the use of DSN, DB_USER and so on. These variable live in the dbsettings file.
*/
$db = new PDO(DSN,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
}
?>
Then you might want to create a class to register your user like:
<?php
//Include the database class file to allow access to properties and methods within that class.
require_once 'class.database.php';
//echo 'I am database class file now included in the users class file. <br />';
//This method will be user to check if the user enter the correct username password pair.
class users{
public function checkValidUser($username){
$userExists = false;
try {
$db = database::databaseConnect();
$stmt = $db->prepare('SELECT uname FROM table WHERE uname=:username');
$stmt->bindParam(':uname', $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1){
$userExists = true;
}
$db = null;
} catch (PDOException $e) {
$userExists = false;
}
return $userExists;
}
public function addUser($firstname, $lastname, $username,$password){
$success = true;
//Connect to the database
try {
$db = database::databaseConnect();
//$db->databaseConnect();
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName, Username, Password) VALUES (:firstname, :lastname, :username, :password)');
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$success = $stmt->execute();
if ($success){
$success = true;
}
$db = null;
} catch (PDOException $e) {
//echo 'There was an error adding a new user. Please go back and try again. If this problem persits please contact the administrator.';
$success = false;
}
return $success;
}
?>
Hope that this helps.
enter link description here$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
You're not inserting the values into proper fields, it appears. You're inserting the $uname into L1 and md5($pword) into L2 but in the select query above, you have a different field name for username and I presume the same for password.
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
Most likely, your insert query should be something like:
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
I added single quotes around the username and password since presumably they are strings. Also, I added curly braces around the variables to segregate what is SQL from what is PHP.
One last thing, I would check into doing this with PDO as Willem suggested

Categories